「jQuery」eachメソッドでDOM要素に採番したIDを割り振るサンプル
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.0
構文
$(要素).each(function (インデックス, 要素) {
// 繰り返す処理コード
});
DOM要素(タグ)に対して処理を繰り返します。
書式
$(ボタンのセレクター名).click(function() {
$(“td").each(function() {
処理コード
$(this).attr(属性,値);
attrメソッドで、要素のtdタグに属性のidと属性値の文字列と数値を割り当てています。
使用例
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 50%;
}
table td {
border: 1px solid;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
//ボタン動作
$("#btnchk").click(function() {
let i = 2;
$("td").each(function() {
$(this).attr("class","cft"+i);
i++;
});
});
});
</script>
</head>
<body>
<table>
<tr>
<td>東京</td>
<td>大阪</td>
<td>福岡</td>
</tr>
</table>
<p>
<input type="button" value="検証" id="btnchk" /></p>
</body>
</html>
実行結果
「検証」ボタンを押すと、要素のtdタグに要素のtdタグに属性のidと属性値の文字列と数値を割り当てています。「class="cft2″」、「「class="cft3″」」、「class="cft4″」属性を振り割ります。