複数の要素のプロパティを変更できるようにする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>
参考文献: