且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更改所有列表项的属性值?

更新时间:2023-10-23 09:54:22

你的选择器有点不对

$("#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).