我如何遍历类名,我不能wrap
,也不能为它们添加id+var
,问题是:
$('.meteo')
返回一个 list
,因此,$('.meteo')[0]
将返回第一个元素,但为什么我不能在循环中操作它呢?例如:
for (h = 0; h < 4; h++) {
$('.meteo')[h].attr('id', 'meteo'+h);
}
最佳答案
这是因为您在非 jQuery object 上使用了 jQuery 方法 .attr()
.
$('.meteo')[0]
,成为 native DOM element ,并且它没有 jQuery 方法。
您可以使用 .eq()
method通过索引访问元素:
$('.meteo').eq(h).attr('id', 'meteo' + h);
您也可以直接更改 id
属性:
$('.meteo')[h].id = 'meteo' + h;
或者..
document.querySelectorAll('.meteo')[h].id = 'meteo' + h;
关于javascript - 无法将带有变量的 id 添加到类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29290182/