2013-05-13 3 views
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 
} 

Я надеюсь, что кто-то поможет мне. Заранее спасибо.

+1

Метод ['eq()'] (http://api.jquery.com/eq/) или [': eq()'] (http://api.jquery.com/eq -селектор /) селектор? И какие свойства вы хотите изменить, точно; скорее всего, это будет лучше и проще. –

+1

Почему бы не использовать метод 'each'? – undefined

ответ

6

Вы можете использовать $.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); 
}); 
2
for (var i = 0; i < $('#parent').children().length; i++) 
$('#parent').find(":eq("+i+")"); 
} 

Fiddle

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> 

Ссылки: