DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> js檢查頁面上有無重復id的實現代碼
js檢查頁面上有無重復id的實現代碼
編輯:關於JavaScript     

方法一:

復制代碼 代碼如下:
<!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;
        for(var i = 0; i < 2000; i++){
            id = "divId" + parseInt(Math.random() * 10000);
            html.push("<div id='" + id + "'>" + id + "</div>");
        }
        document.body.innerHTML = html.join("");
    }
    window.onload = function(){
        createDiv();

        var oID = {} , result = {}, arr = [],
            tags = document.getElementsByTagName("*");
        for(var i = 0, id; i < tags.length; i++){
            id = tags[i].id;
            if(id){
                oID[id] = oID[id] ? oID[id] + 1 : 1;
                if(oID[id] > 1){
                    result[id] = id + " " + oID[id]; } } } for(var o in result){
            arr.push(result[o]);
        }
        alert(arr.join("/t"));
    };
  </script>
</HEAD>
<BODY>
</BODY>
</HTML>

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved