选择组的jQuery对象比$($(“。someclass”)))更简单的方法?
所以我试图循环遍历“someclass”的成员,而不是DOM元素,而是他们的jQuery对应物。 我一直在使用$($(“。someclass”)[i]),但这非常难看。 有更自然的方式吗?
你可以使用eq()方法:
$(".someclass").eq(i);
也就是说,Felix Kling是对的:您最好使用each()而不是循环来迭代存储在jQuery对象中的元素。
使用.each()
[docs]迭代元素:
$(".someclass").each(function() { // use $(this) });
你可以使用jquery的nth-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("" + (i+1) + ""); });
(像往常一样,回调函数中的参数是可选的。)
一些操作元素的方法可以采用回调方法,因此您可以使用它来迭代元素。 例:
$(".someclass").append(function(i, h){ // i is the index // h is the current html content // Return html to append: return "" + (i+1) + ""; });
试试:
$(".someclass:eq("+yourNumberHere+")")