比$($(".someclass")[i]))更简单的选择jQuery对象组的方法

Easier way to select ith jQuery object of group than $($(".someclass")[i]))?

本文关键字:quot 选择 jQuery 方法 对象 someclass 更简单      更新时间:2023-09-26

所以我试图通过"someeclass"的成员循环,而不是DOM元素,但他们的jQuery对应物。我一直在使用$($(". someeclass ")[I]),但这很难看。有没有更自然的方法?

您可以使用eq()方法:

$(".someclass").eq(i);

也就是说,Felix Kling是正确的:您最好使用each()而不是循环来遍历存储在jQuery对象中的元素。

使用.each() [docs]来遍历元素:

$(".someclass").each(function() {
    // use $(this)
});

可以使用jquery的n -child

$("ul li:nth-child(1)").addClass("green"); //this select 1 the element  of group

您可以使用each方法来迭代元素:

$(".someclass").each(function(i, e){
  // i is the index
  // e is the element
  // this is the element
  // $(this) is the element wrapped in a jQuery object
  $(this).append("<span>" + (i+1) + "</span>");
});

(回调函数中的参数通常是可选的)

一些操作元素的方法可以采用回调方法,这样就可以使用回调方法来迭代元素。例子:

$(".someclass").append(function(i, h){
  // i is the index
  // h is the current html content
  // Return html to append:
  return "<span>" + (i+1) + "</span>";
});

尝试:

$(".someclass:eq("+yourNumberHere+")")