我正在用ASP.NET MVC编写应用程序.与传统的ASP.NET相比,您更负责在生成的页面中创建所有ID.ASP.NET会给你讨厌但独特的ID.
我想添加一个快速的小jQuery脚本来检查我的文档是否有重复的ID.它们可能是DIVS,图像,复选框,按钮等的ID.
<div id="pnlMain"> My main panel </div>
<div id="pnlMain"> Oops we accidentally used the same ID </div>
Run Code Online (Sandbox Code Playgroud)
我正在寻找一套设置和忘记类型的实用程序,当我做一些不小心的事情时,它会警告我.
是的我只在测试期间使用它,并且也欢迎替代品(例如firebug插件).
小智 205
以下内容将向控制台记录警告:
// Warning Duplicate IDs
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if(ids.length>1 && ids[0]==this)
console.warn('Multiple IDs #'+this.id);
});
Run Code Online (Sandbox Code Playgroud)
Sjo*_*erd 32
这个版本有点快,你可以将它复制到书签按钮,使其成为书签.
javascript:(function () {
var ids = {};
var found = false;
$('[id]').each(function() {
if (this.id && ids[this.id]) {
found = true;
console.warn('Duplicate ID #'+this.id);
}
ids[this.id] = 1;
});
if (!found) console.log('No duplicate IDs found');
})();
Run Code Online (Sandbox Code Playgroud)
Aut*_*nge 14
我有一个大页面,因此脚本运行得太慢而无法完成(多个"继续脚本"消息).这很好用.
(function () {
var elms = document.getElementsByTagName("*"), i, len, ids = {}, id;
for (i = 0, len = elms.length; i < len; i += 1) {
id = elms[i].id || null;
if (id) {
ids[id] = ids.hasOwnProperty(id) ? ids[id] +=1 : 0;
}
}
for (id in ids) {
if (ids.hasOwnProperty(id)) {
if (ids[id]) {
console.warn("Multiple IDs #" + id);
}
}
}
}());
Run Code Online (Sandbox Code Playgroud)
你为什么不验证你的HTML?
不允许使用双重身份证,通常您会收到解析错误.
顶级 jQuery 答案,用 ES6 重写:
[...document.querySelectorAll('[id]')].forEach(el => {
const dups = document.querySelectorAll(`[id="${el.id}"]`);
if (dups[1] === el) {
console.error(`Duplicate IDs #${el.id}`, ...dups);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46120 次 |
| 最近记录: |