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

时间:2021-05-26

方法一:

复制代码 代码如下:
<!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>

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章