0
:nth-child() 

- 是一个选择器,用于选择作为其父元素的第 n 个子元素的每个元素。

有没有办法使用索引值来选择父母的孩子?我想单独获取和设置每个孩子的属性。我的代码结构是:

for (var i=0;i<length;i++) {
  //Create a selector that will choose the first child using `index` value
  //Change each child's properties
}

我希望有人能帮助我。提前致谢。

4

3 回答 3

5

您可以使用$.each()

简单示例(jsFiddle):HTML:

<table>
    <tr id="test">
         <td>a</td>
         <td>b</td>
         <td>c</td>
         <td>d</td>
         <td>e</td>
    </tr>
<table>

jQuery:

$.each($("#test").children(), function(index, data){
       alert(index);
});
于 2013-05-13T07:52:15.253 回答
2
for (var i = 0; i < $('#parent').children().length; i++)
 $('#parent').find(":eq("+i+")");
}

小提琴

于 2013-05-13T07:55:28.643 回答
2

您正在尝试做的事情过于复杂,大多数允许更改多个元素的属性的 jQuery 方法也允许一个匿名函数迭代每个元素,例如更改多个元素的文本:

var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

// selects the '#container' element's children
$('#container').children()
/* the text method accepts an anonymous function,
   the first parameter is the index of the current element returned by the selectors,
   the second parameter is the 'current' value (so the current text of the element) */
.text(function (i, t) {
    // sets the text to be the current-text + the new string + the index of the element
    return t + ', of index ' + i;
})
// using an object to set multiple CSS properties:
.css({
    // setting the color to the color from the colors array with the same index:
    'color': function (i) {
        return colors[i];
    },
    // increasing the text-indent by 1em for every element
    'text-indent': function (i) {
        return (i * 1) + 'em';
    }
}).filter(function(i){
    /* keeps only those elements whose index, mod 2, is equal to 0
       (so the elements whose index is an even number) */
    return i%2 == 0;
}).css('font-weight', 'bold');;

JS 小提琴演示

上面使用了这个基本的 HTML:

<div id="container">
    <div>child of "#container"</div>
    <div>child of "#container"</div>
    <div>child of "#container"</div>
    <div>child of "#container"</div>
    <div>child of "#container"</div>
    <div>child of "#container"</div>
    <div>child of "#container"</div>
</div>

参考:

于 2013-05-13T09:44:48.230 回答