【发布时间】:2012-12-04 18:21:55
【问题描述】:
如何在javascript中检查包含重复id的标签?
【问题讨论】:
-
检查它们?你一开始就不应该拥有它们。你打算用它们做什么?
-
有时我错误地将id放在多个标签中。
标签: javascript html dom
如何在javascript中检查包含重复id的标签?
【问题讨论】:
标签: javascript html dom
试试这个:
var nodes = document.querySelectorAll('[id]');
var ids = {};
var totalNodes = nodes.length;
for(var i=0; i<totalNodes; i++) {
var currentId = nodes[i].id ? nodes[i].id : "undefined";
if(isNaN(ids[currentId])) {
ids[currentId] = 0;
}
ids[currentId]++;
}
console.log(ids);
【讨论】:
document.querySelectorAll('[id]') 而不是* 将大大减少搜索空间。在小提琴中,它从 14 个元素变为只有 3 个。
这是实现与批准答案相同的更短的方法(计算 ID 的出现次数):
const ids = Array.from(document.querySelectorAll('[id]'))
.map(v => v.id)
.reduce((acc, v) => { acc[v] = (acc[v] || 0) + 1; return acc }, {});
console.log(ids);
如果只需要重复 ID 列表,则可以过滤条目:
Object.entries(ids)
.filter(([key, value]) => value > 1)
.map(([ key, value]) => key)
【讨论】:
我认为你真正需要的是在使用它之前检查该 id 或命名空间是否已经被占用,而不是在你使用它之后检查你是否犯了错误......
我早在 2006 年左右就已经编写了这个函数。可能更早 它会检查该 id 是否已被占用。
(它的功能更多,但这是最基本的用途)
function isNS( arg, f ) {
if(typeof arg!="string")throw( 'TYPE_ERROR:"string required"');
var i, a = arg.split("."), c = this, s = [], b, r;
f = f || 0;
for( i in a ) {
c ? a[i] in c ? ( c = c[ a[i] ], s.push( a[i] ), b = !0 ) :
b = !1 : 0;
}
r = [ b, c, s, a, arg ];
return f < 0 ? r : r[+f||f];
}
;
console.log( isNS("par") )
<p id=par>Paragraf with id "par"
【讨论】: