熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

js檢查頁面上有無重復id的實現代碼

2022-06-13   來源: JSP教程 
有時候我們需要檢查一個頁面上是否用重復的id一般id都是唯一的也方便控制那麼就可以參考下面的代碼  

  方法一

復制代碼 代碼如下:
<!DOCTYPE HTML PUBLIC "//WC//DTD HTML Transitional//EN">
<HTML>
<HEAD>
  <TITLE> New Document </TITLE>
  <script type="text/javascript">
    windowonload = function(){
        var tags = documentgetElementsByTagName("*")
            count = tagslength time ret = {} id;
        time = new Date();
        for(var i = ; 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(Mathrandom() * );
        for(var i = ; i < ; i++){
            htmlpush("<div id=a" + i + ">" + i + "</div>");
        };
        //在隨機位置插入一個隨機的id
        i = parseInt(Mathrandom() * );
        html[i] = html[i] + ("<div id=a" + rnd + ">" + rnd + "</div>");
        documentwrite(htmljoin(""));
    })();
  </script>
</BODY>
</HTML>

  方法二

復制代碼 代碼如下:

  
<!DOCTYPE HTML PUBLIC "//WC//DTD HTML Transitional//EN">
<HTML>
<HEAD>
  <TITLE> New Document </TITLE>
  <script type="text/javascript">
    function createDiv(){
        var html = [] id;
        for(var i = ; i < ; i++){
            id = "divId" + parseInt(Mathrandom() * );
            htmlpush("<div id=" + id + ">" + id + "</div>");
        }
        documentbodyinnerHTML = htmljoin("");
    }
    windowonload = function(){
        createDiv();

        var oID = {} result = {} arr = []
            tags = documentgetElementsByTagName("*");
        for(var i = id; i < tagslength; i++){
            id = tags[i]id;
            if(id){
                oID[id] = oID[id] ? oID[id] + : ;
                if(oID[id] > ){
                    result[id] = id + " " + oID[id]; } } } for(var o in result){
            arrpush(result[o]);
        }
        alert(arrjoin("/t"));
    };
  </script>
</HEAD>
<BODY>
</BODY>
</HTML>


From:http://tw.wingwit.com/Article/program/Java/JSP/201311/20641.html
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.