$(".focus-button").addClass('active');
$(".focus-button[data-expand='true']").addClass('active');
If I store the class selector in a variable like:
var btn = $(".focus-button");
The variable can be used in the code as
btn.addClass('active'); // This is correct
btn[data-expand='true'].addClass('active'); // This is wrong
May I know what is the right way to use variable with attributes.
You can use filter to add additional selectors in the way you want.
Reduce the set of matched elements to those that match the selector or pass the function's test.
Example:
var btn = $(".focus-button");
btn.addClass("active");
btn.filter("[data-expand='true']").removeClass("active")
Where
var btn = $(".focus-button");
btn.filter("[data-expand='true']")
is the same as
$(".focus-button[data-expand='true']")
Situation:
In your actual code, if you write:
var btn = $(".focus-button");
You will get a collection of all elements with class focus-button
, so when you write, btn.addClass('active');
it's correct and it will add the class active
to all the elements in this collection.
Problem:
While when you write:
btn[data-expand='true'].addClass('active');
It's wrong because JavaScript will interpret it as you are accessing a property in your btn
object, because []
are only used to access a specific property
in an object
or a specific element by index
in an array
.
And btn[data-expand='true']
is only a CSS selector.
Solution:
You can use jQuery .filter() as suggested in comments, like this:
btn.filter("[data-expand='true']").addClass('active');
try this snippet:
//$(".focus-button").addClass('active'); //$(".focus-button[data-expand='true']").addClass('active'); var btn = $(".focus-button"); //btn.addClass('active'); btn.filter("[data-expand='true']").addClass('active');
.active{ background: #000; color: #fff; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="focus-button">F</div> <div class="focus-button" data-expand="true">E</div>
试试这个代码
btn.filter("data-expand='true'").addClass('active');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.