有时候我们需要检查一个页面上是否用重复的id
一般id都是唯一的
也方便控制
那么就可以参考下面的代码
方法一
复制代码 代码如下:
<!DOCTYPE HTML PUBLIC "
//W
C//DTD HTML
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 =
; 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() *
);
for(var i =
; i <
; i++){
html
push("<div id=
a" + i + "
>" + i + "</div>");
};
//在随机位置插入一个随机的id
i = parseInt(Math
random() *
);
html[i] = html[i] + ("<div id=
a" + rnd + "
>" + rnd + "</div>");
document
write(html
join(""));
})();
</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>