但使用这段代码,所有复选框元素都具有相同的 id...
var count;
var length = $('input[type=checkbox]').length
for(count=1;count<=length;count++){
$('input[type=checkbox]').attr('id',count)
}
最佳答案
使用 .prop() 或 .attr() 设置元素 ID
$(':checkbox').prop("id", function( i ){
return i;
});
使用 .each() 设置元素 ID
$(':checkbox').each(function( i ){
this.id = i;
});
两个例子都返回:
<input id="0" type="checkbox">
<input id="1" type="checkbox">
<input id="2" type="checkbox">
<input id="3" type="checkbox">
如果你想从 1 开始,只需使用:
this.id = i+1;
由于非 HTML5(旧版)浏览器不支持数字 ID,请将任何字符串 prefix 添加到 ID 编号,例如 "el"+ (i+1)
关于javascript - 增量元素 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16375926/