想象一下,您有以下三个jQuery对象a, b, c,
如何在不重复太多代码的情况下为所有这些对象设置相同的属性:
a.attr({
"first": "sameFirst",
"second": "sameSecond",
"third": "sameThird",
});
b.attr({
"first": "sameFirst",
"second": "sameSecond",
"third": "sameThird",
});
c.attr({
"first": "sameFirst",
"second": "sameSecond",
"third": "sameThird",
});
不是这样的:
$(a, b, c).attr({
"first": "sameFirst",
"second": "sameSecond",
"third": "sameThird",
});
编辑:现在我了解到我可以使用.add()
或$()
使用非jQuery对象数组,我想知道为什么$(a, b, c)
isn&# 39;支持,因为我的其他解决方案似乎不必要地冗长或复杂。
答案 0 :(得分:2)
不存在类似的内容:
$(a, b, c).attr({
...
不,但你有两个相似的选择:
.add
(这可能是最简单和最清晰的)
$()
这是add
:
var a = $("#a"),
b = $("#b"),
c = $("#c");
a.add(b).add(c).css("color", "green");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="a">a</div>
<div id="b">b</div>
<div id="c">c</div>
这是元素数组的$()
:
var a = $("#a"),
b = $("#b"),
c = $("#c");
$(a.get().concat(b.get()).concat(c.get())).css("color", "green");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="a">a</div>
<div id="b">b</div>
<div id="c">c</div>
或者,如果你知道,每个jQuery对象中只有一个元素,那么它就更简单了:
var a = $("#a"),
b = $("#b"),
c = $("#c");
$([a[0], b[0], c[0]]).css("color", "green");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="a">a</div>
<div id="b">b</div>
<div id="c">c</div>
我想知道为什么
$(a, b, c).foo()
不受支持,因为我的其他解决方案似乎不必要地冗长或复杂。
$()
函数已经荒谬重载(see docs),我的猜测是,这是在某些时候没有添加的唯一原因。令人惊讶的是,很少出现这种情况。
答案 1 :(得分:0)
$.each([a,b,c], function (index, item) {// do stuff here with item});
答案 2 :(得分:0)
尝试
var a = $("#a"), b = $("#b"), c = $("#c");
var attrs = {
"first": "sameFirst",
"second": "sameSecond",
"third": "sameThird",
};
$([]).pushStack([a[0], b[0], c[0]]).attr(attrs)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="a">a</div>
<div id="b">b</div>
<div id="c">c</div>
&#13;
替代地
var a = $("#a"), b = $("#b"), c = $("#c");
var attrs = {
"first": "sameFirst",
"second": "sameSecond",
"third": "sameThird",
};
$([a, b, c]).map(function() {
$(this).attr(attrs);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="a">a</div>
<div id="b">b</div>
<div id="c">c</div>
&#13;