简体   繁体   English

在Javascript中使用变量保持选择器

[英]Using variable holding selectors in Javascript

$(".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'); 您将使用class focus-button获得所有元素的集合,因此在编写时, btn.addClass('active'); it's correct and it will add the class active to all the elements in this collection. 是正确的,它将把active类添加到此集合中的所有元素。

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 . 这是错误的,因为JavaScript将在您访问btn对象中的属性时对其进行解释,因为[]仅用于按arrayindex访问object的特定property或特定元素。

And btn[data-expand='true'] is only a CSS selector. btn[data-expand='true']只是一个CSS选择器。

Solution: 解:

You can use jQuery .filter() as suggested in comments, like this: 您可以按照注释中的建议使用jQuery .filter() ,如下所示:

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'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM