javascript - 无法将带有变量的 id 添加到类中

标签 javascript jquery

我如何遍历类名,我不能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/

相关文章:

javascript - 读取javascript脚本index.html公共(public)文件夹中的类react js

javascript - 优化对象重叠检测 (Javascript)

Javascript/jQuery : Make second file input button visible only after first file input button has selected a file

javascript - Bootstrap 工具提示和弹出窗口 : To Destroy, 或不销毁?

java - Jquery + PHP : Grabbing the autocomplete strings from a third party php script

jquery - 在 jquery 的隐藏文本字段中传递变量值

jquery - HTML、jQuery : Show text over area of image-map

javascript - 情感/样式 - 将鼠标悬停在 SVG 组件上

javascript - javascript src url 中的动态值

javascript - 在运行时更改所有 CSS 属性