約 800 のフィールドを含むフォームを作成しました。知らず知らずのうちに、フォームのいくつかのフィールドに同じ ID を指定してしまいました。それらを追跡する方法は?
6 に答える
http://validator.w3.org/が便利なソリューションになります。しかし、jqueryを使用すると、次のようなことができます。
//See your console for duplicate ids
$('[id]').each(function(){
var id = $('[id="'+this.id+'"]');
if(id.length>1 && id[0]==this) {
console.log('Duplicate id '+this.id);
alert('duplicate found');
}
});
お役に立てれば。
これはあなたを助けるかもしれません
HTMLページで重複するIDを見つける
2011年5月6日にエネコアロンソによって書かれました
要素IDがHTMLページで一意であることを意味していることを忘れていることがあるようです。これは、ページ上で重複するIDを見つけるために作成したコードの一部です(ブラウザーのjavascriptコンソールでコードを実行します)。
var idList = {};
var nodes = document.getElementsByClassName('');
for (var i in nodes) {
if (!isNaN(i) && nodes[i].id) {
idList[nodes[i].id] = idList[nodes[i].id]? idList[nodes[i].id]+1:1;
}
}
for (var id in idList) {
if (idList[id] > 1) console.log("Duplicate id: #" + id);
}
配列メソッドのみを使用した 1 つのライナー:
[].map.call(document.querySelectorAll("[id]"),
function (e) {
return e.id;
}).filter(function(e,i,a) {
return ((a.lastIndexOf(e) !== i) && !console.log(e));
})
すべての重複をログに記録し、見つかった場合は ID を含む配列を返します。
例を作成しました。これは、ページ上のフォーム/要素内の重複 ID をすべて見つけ、重複 ID 名をコンソールに出力します。
配列contains
メソッドは、この投稿から取得されました。
<html>
<body>
<form id="frm">
<input type="text" id="a" />
<input type="text" id="b" />
<input type="text" id="c" />
<input type="text" id="d" />
<input type="text" id="e" />
<input type="text" id="f" />
<input type="text" id="a" />
<input type="text" id="h" />
<input type="text" id="i" />
<input type="text" id="j" />
<input type="text" id="d" />
<input type="text" id="l" />
</form>
</body>
<script type="text/javascript">
Array.prototype.contains = function(obj) { //Add a 'contains' method to arrays
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
frm = document.getElementById('frm'); //Get the form
els = frm.getElementsByTagName('input'); //Get all inputs within the form
ids = new Array(els.length); //Create an array to hold the IDs
for(e = 0; e < els.length; e++) { //Loop through all of the elements
if(ids.contains(els[e].id)) //If teh array already contains the ID we are on
console.log('Duplicate: '+els[e].id); //Print 'Duplicate: {ID}' to the console
ids.push(els[e].id); //Add the ID to the array
}
</script>
</html>
上記のコードは次を出力します。
複製: a
重複: d
Dup-ID という名前の Chrome 拡張機能があります。これをインストールすると、ボタンを押すだけで重複した ID を確認できます。インストールのリンク: https://chrome.google.com/webstore/detail/dup-id-scans-html-for-dup/ngpgpgolddgjmkjioagggmnmddbgedice
デフォルトでは、メモ帳++には構文の強調表示があり、1つの単語をダブルクリックして選択すると、同じ単語の他のすべての出現が強調表示されます。フィールドには独自の名前を付けることができないため、名前を変更するためにいくつかの (おそらく多くの) 手作業を行う必要があります。