我如何addClass或将css属性添加到分配了变量的多个元素(id' s)。如果我直接使用$('#cc, #dd').addClass('blue')
代码,但如果将变量分配给id $(cc, dd).addClass('blue')
等ID,则代码无效。请检查以下代码,注释行有效,但如果有变量则不行。
$(document).ready(function() {
var cc = $("#cc"),
dd = $("#dd");
$("button").click(function() {
// $("#cc, #dd").addClass("blue");
$(cc, dd).addClass("blue");
$(cc, dd).css({
"color": "#2196f3",
"font-size": "30px"
});
$("h1, h2, p").addClass("blue");
});
});

.blue {
color: #2196f3;
font-size: 30px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div id="cc">hello 1</div>
<div id="dd">hello 2</div>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>This is a paragraph.</p>
<button>Add classes to elements</button>
&#13;
答案 0 :(得分:3)
使用add()将dd元素添加到cc集合中,此时您正尝试在dd元素中查找cc元素,请参阅selector context
var cc = $("#cc"),
dd = $("#dd");
$(cc).add(dd).addClass("blue");
&#13;
.blue {
background:blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="cc"></button>
<button id="dd"></button>
&#13;
答案 1 :(得分:0)
$(document).ready(function() {
var cc = $("#cc"),
dd = $("#dd");
$("button").click(function() {
// $("#cc, #dd").addClass("blue");
dd.addClass("blue");
cc.addClass("blue");
$(cc, dd).css({
"color": "#2196f3",
"font-size": "30px"
});
//$("h1, h2, p").addClass("blue");
});
});
.blue {
color: #2196f3;
font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div id="cc">hello 1</div>
<div id="dd">hello 2</div>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>This is a paragraph.</p>
<button>Add classes to elements</button>
答案 2 :(得分:0)
您可以使用数组并加入:
var arrSelectors = ["#cc", "#dd", ".someOtherSelector"];
$(arrSelectors.join).addClass("blue");