Jquery - 获取第 x 个元素

发布于 2024-07-15 13:19:14 字数 163 浏览 2 评论 0原文

例如,我有一个带有 id 的 div(假设为“the_div”)。 这个div包含一个无序列表,这个列表中有5个项目。

如何在没有任何列表项附加有类的情况下将类添加到第三个列表项?

编辑:更好的是,我如何将列表项文本更改为等于它的数字元素?

谢谢。

For example, I have a div with an id (lets say "the_div"). This div contains an unordered list, and this list has 5 items in it.

How would I add a class to the third list item, without any of the list items having a class attached to them?

Edit: Even better, how would I change the list item text to equal what number element it was?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

说好的呢 2024-07-22 13:19:14

或者...

$('#the_div ul li:eq(2)').addClass('className');

您可以将选择器组合在一起 - 如果您愿意:)

Or...

$('#the_div ul li:eq(2)').addClass('className');

You can combine the selectors together - if you prefer :)

巨坚强 2024-07-22 13:19:14

对于第一个问题,您可以使用 eq ,是基于 0 的:

$('ul li', '#thediv').eq(2).addClass('whatever'); // add class to 3rd item

对于第二个问题,您可以使用 each 迭代所有列表项。 回调函数传递一个包含集合中当前元素索引的参数:

$('ul li', '#thediv').each(function(i) {
    $(this).text(i); // update each list item with its index, 0 based.
});

For your first problem, you can use eq, which is 0 based:

$('ul li', '#thediv').eq(2).addClass('whatever'); // add class to 3rd item

For your second problem, you can use each to iterate through all the list items. The callback function passes an argument containing the index of the current element in the set:

$('ul li', '#thediv').each(function(i) {
    $(this).text(i); // update each list item with its index, 0 based.
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文