首页 > 语言 > JavaScript > 正文

js检查页面上有无重复id的实现代码

2024-05-06 14:37:35
字体:
来源:转载
供稿:网友

方法一:

代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE> New Document </TITLE>
  <script type="text/javascript">
    window.onload = function(){
        var tags = document.getElementsByTagName("*"),
            count = tags.length, time, ret = {}, id;
        time = new Date();
        for(var i = 0; i < count; i++){
            id = tags[i].id;
            if(id){
                if(ret[id]){
                    alert(id + "/n用时:" + (new Date() - time));
                    return;
                }else{
                    ret[id] = true;
                }
            }
        }
        alert("未找到相同ID");
    }
  </script>
</HEAD>
<BODY>
  <script type="text/javascript">
    (function(){
        var html = [], rnd = parseInt(Math.random() * 1000);
        for(var i = 0; i < 1000; i++){
            html.push("<div id='a" + i + "'>" + i + "</div>");
        };
        //在随机位置插入一个随机的id
        i = parseInt(Math.random() * 1000);
        html[i] = html[i] + ("<div id='a" + rnd + "'>" + rnd + "</div>");
        document.write(html.join(""));
    })();
  </script>
</BODY>
</HTML>

方法二:

代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE> New Document </TITLE>
  <script type="text/javascript">
    function createDiv(){
        var html = [], id;

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选