使用索引选择父级的子级

时间:2013-05-13 07:45:46

标签: jquery jquery-selectors

: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
}

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

3 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分:2)

for (var i = 0; i < $('#parent').children().length; i++)
 $('#parent').find(":eq("+i+")");
}

Fiddle

答案 2 :(得分: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 Fiddle demo

以上使用此基础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>

参考文献: