简体   繁体   English

添加类“active”以跨越 JQuery 或 JavaScript

[英]Add class "active" to span with JQuery or JavaScript

I have three spans我有三个跨度

$(".regions_list li span")
[
<span>​text0</span>​
, 
<span>text1​</span>​
, 
<span>​text2</span>​
]

I want to add active class for span that text equal with myVariable我想为与myVariable相等的文本添加活动类

  myVariable = "text2";
  $(".regions_list li span").eq(myVariable).addClass("active");

but this method doens't work for this example.但此方法不适用于此示例。

some proposal?一些建议?

Using jQuery, use the contains selector to select all elements that contain the specified text:使用 jQuery,使用contains选择器选择包含指定文本的所有元素:

var myVariable = "text2";
$(".regions_list li span:contains(" + myVariable + ")").addClass("active");

Notice: You have no guarantee with this solution that only "text2" spans elements would be selected because contains functioning pretty much like the SQL like clause, it will select whatever starts or ends with the given text.注意:您无法保证此解决方案只会选择“text2”跨度元素,因为它contains功能与 SQL like子句非常相似,它将选择以给定文本开头或结尾的任何内容。 You may enforce exact-match comparison on it as @xec suggested :您可以按照@xec 的建议对其进行精确匹配比较:

$(".regions_list li span").filter(function(){
    return $(this).text() === myVariable;
}).addClass("active");

Look at my jsFiddle example: http://jsfiddle.net/ynevet/337NV/看看我的 jsFiddle 示例: http : //jsfiddle.net/ynevet/337NV/

You can use :contains()您可以使用:contains()

$(".regions_list li span:contains('"+myVariable+"')").addClass("active");

DEMO演示

Although contains work, I personally think, you can do this ( See bottom for why ):虽然contains工作,但我个人认为,您可以这样做(原因见底部):

$(".regions_list li span").filter(function(){
   return $(this).text() == myVariable;
}).addClass("active");

Take a look at jsperf .看看jsperf This method is the fastest and most efficient.这种方法是最快、最有效的。

contains is slow when compared to filter .filter相比, contains速度较慢。

Like some other answers suggest, using :contains() can work, as long as it doesn't need to be an exact match.就像其他一些答案所暗示的那样,只要不需要完全匹配,就可以使用:contains() :contains(text2) will match <span>text2</span> as well as potentially false positives, such as <span>text23</span> . :contains(text2)将匹配<span>text2</span>以及潜在的误报,例如<span>text23</span>

If you need an exact match, you could use a custom filter instead;如果您需要完全匹配,则可以改用自定义过滤器;

$(".regions_list li span").filter(function(){
    return $(this).text() === myVariable;
}).addClass("active");

http://jsfiddle.net/baJLx/4/ http://jsfiddle.net/baJLx/4/

使用包含jquery 的选择器

$("span:contains('"+myVariable+"')").addClass("active");

You can try below code:你可以试试下面的代码:

Working Demo工作演示

var myVariable = "text1";
$(".regions_list li span:contains("+myVariable+")").addClass("active");

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

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