简体   繁体   English

如何从jquery中的div列表中选择属性?

[英]How to select attributes from a list of divs in jquery?

I have 16 divs with the class "box" and each "box" has a different name.我有 16 个带有“box”类的 div,每个“box”都有不同的名称。

The first "box" has name="box1";
the second "box" has name="box2";
the third "box" has name="box3";
and so on.....

I want to select these individual names, so I attempted to use the following code:我想选择这些单独的名字,所以我尝试使用以下代码:

for (var i = 0; i < $(".box").length; i++) {
  console.log($(".box")[i].attr("name"));
}

But my console shows that "$(...)[i].attr is not a function".但是我的控制台显示“$(...)[i].attr 不是函数”。

When I tried this:当我尝试这个时:

for (var i = 0; i < $(".box").length; i++) {
  console.log($(".box").attr("name"));
}

I get back 16 lines of "box1", which is only the name for the first "box" div.我得到 16 行“box1”,这只是第一个“box”div 的名称。

What I want instead is "box1, box2, box3, box4, box5..."我想要的是“box1、box2、box3、box4、box5……”

What can I do?我能做什么?

Does it have to be jQuery?它必须是jQuery吗? If not, this could work:如果没有,这可以工作:

[...document.querySelectorAll('.box')]
  .map(d => d.getAttribute('name'))
  .forEach(name => console.log(name))

Using jQuery:使用jQuery:

$( ".box" ).each(function( index ) {
  console.log($(this).attr("name") );
});

You can do it using jQuery eq你可以使用 jQuery eq

for (var i = 0; i < $(".box").length; i++) {
  console.log($(".box").eq(i).attr("name"));
}

or using fully jQuery version或使用完整的 jQuery 版本

$('.box').each(function(){
  console.log($(this).attr('name'));
})

Please note that name is not a supported attribute on div elements, hence making your HTML invalid .请注意name不是div元素上受支持的属性,因此会使您的 HTML无效 Use data-name instead.请改用data-name Once you changed that, that also makes the code easier:一旦你改变了它,这也会使代码更容易:

$(".box")[i]

gives you the native DOM element in the jQuery collection, which does not have any jQuery methods like attr() .为您提供 jQuery 集合中的原生 DOM 元素,它没有任何像attr()这样的 jQuery 方法。 It does, tho, have the native DOMElement dataset API, so you can simply go with它确实具有本机 DOMElement dataset API,因此您可以简单地使用

$(".box")[i].getAttribute('data-name')

or, even simpler或者,甚至更简单

$(".box")[i].dataset.name

If you insist on using jQuery and also on using an index-based for -loop (which I haven't used in years now), go with jQuery's eq(index) function:如果您坚持使用 jQuery并且还坚持使用基于索引的for循环(我已经好几年没有使用了),请使用 jQuery 的eq(index)函数:

$(".box").eq(i).data("name")

As with almost everything, jQuery is just unnecessary bloat you don't need any longer in 2020. Here's the modern way to achieve your goal:与几乎所有东西一样,jQuery 只是不必要的膨胀,您在 2020 年不再需要它。这是实现目标的现代方法:

document.querySelectorAll('.box')
  .forEach(el => console.log(el.dataset.name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM