如何更改所有列表项的属性值? [英] How can I change an attribute value for all list items?

查看:24
本文介绍了如何更改所有列表项的属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的结构,如:

I have a simple structure like:

HTML

<ul id="costsDropdown">
    <li data-position="bla bla"></li>
</ul>

并且我想更改列表元素的每个数据位置"属性.

and I want to change each "data-position" attribute of my list Elements.

我的第一个 Jquery 镜头是在这里:

My first Jquery Shot was this here:

$("#costsDropdown ul").each(function() {
    $("li").attr("data-position", "TEST-VALUE123");
});

但它不起作用,我认为我的选择器是错误的...

but it doesnt work, I think my selector are wrong...

有人可以给我一个提示吗?

could anyone give me a hint please?

感谢您的帮助!

问候

推荐答案

你的选择器有点不对

$("#costsDropdown ul").each

即试图选择容器 #costsDropdown 的子 ul(这是 ul 的 ID) - 你想要什么是:

That is trying to select the child ul of the container #costsDropdown (which is the ID of the ul) - what you want is:

$("#costsDropdown li").each(function() {
    $(this).attr("data-position", "TEST-VALUE123");
});

ID 是唯一的 - 无需将带有 ID 元素类型的选择器加倍.

ID's are unique - no need to double up the selector with an ID and the type of element it is.

请注意,我在 each 回调中使用了 $(this),而不是 $("li").$("li") 选择页面上任意位置的所有 li 元素;我们只需要一个 jQuery 包装器,用于我们在 each 中处理的特定包装.

Note that I used $(this), not $("li"), inside the each callback. $("li") selects all li elements, anywhere on the page; we just want a jQuery wrapper for the one specific one we're handling inside the each.

事实上,由于jQuery的基于集合的特性,each是完全没有必要的;如果您使用 .attr setter,它会在集合中的所有元素上设置属性:

In fact, the each is completely unnecessary because of the set-based nature of jQuery; if you use the .attr setter, it sets the attribute on all elements in the set:

$("#costsDropdown li").attr("data-position", "TEST-VALUE123");

这将在 #costsDropdown 内的 所有 li 元素上设置值.

That will set the value on all of the li elements inside #costsDropdown.

如果你需要在单独的 li 元素上设置单独的单独值,你仍然不需要 each(尽管如果你想使用它也没关系);您可以使用接受回调的 attr 版本,该回调用于找出要设置的值:

If you need to set separate individual values on the individual li elements, you still don't need each (though it's fine if you want to use it); you can use the version of attr that accepts a callback that it uses to find out what value to set:

$("#costsDropdown li").attr("data-position", function(index) {
    return "Test value " + index;
});

这将在第一个 li 上设置 "Test value 0",在第二个上设置 "Test value 1",等等.上面的 each 示例,如果需要,可以在回调中使用 this 来引用该调用的 li(可能使用 $(this) 如果你需要一个 jQuery 包装器来包装它.

That will set "Test value 0" on the first li, "Test value 1" on the second, etc. And like the each example above, if you need to, you can use this within the callback to refer to the li for that call (possibly using $(this) to wrap it if you need a jQuery wrapper).

这篇关于如何更改所有列表项的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆