您正在尝试做的事情过于复杂,大多数允许更改多个元素的属性的 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>
参考: