idをJQueryで追加する
以前、与えられたhtmlファイルに手でidを100個くらい追加していたが、デザイン変わったらやり直すのかーと思うと悲しくなったので、
idは別途追加したいと思った。
index.htmlのbodyの中身は以下
index.html
<dl id="body">
<button>hoge</button>
<button>fuga</button>
<button>hoga</button>
</dl>
このファイルに以下のjsファイルを読ませる
menu.js
$(function () {
$('button').attr('id', 'hoge');
});
するとindex.htmlにidが追加される。
index.html
<dl id="body">
<button id="hoge">hoge</button>
<button id="hoge">fuga</button>
<button id="hoge">hoga</button>
</dl>
idが振られた。
$('button').attr('id', 'hoge');
と書くと、buttonという要素に新たな要素'id'を要素値'hoge'で追加してくれる。
でも俺がやりたいのは、バラバラのidを付けることなので、menu.jsを変更
menu.js
$(function () {
$('button').eq(0).attr('id', 'hoge');
$('button').eq(1).attr('id', 'fuga');
$('button').eq(2).attr('id', 'hoga');
});
.eq()とすると、何番目かも指定できる。
するとidも変わる。
index.html
<dl id="body">
<button id="hoge">hoge</button>
<button id="fuga">fuga</button>
<button id="hoga">hoga</button>
</dl>
バラバラのidが付けられた。
今回はこれで良いが、以前の100個id手打ちはこのやり方では解決しないんじゃないかなぁ...
おわり