简体   繁体   English

我如何将类添加到特定的html元素(如果它们包含特定值)

[英]How do I add a class to specific html elements, If they contain a certain value

For example, I have the below html: 例如,我有以下html:

<div id="stuff">
<span>1</span><span>2</span><span>3</span>
</div>

And I need to select some in this fashion: 我需要以这种方式选择一些:

$('#stuff').find('<span>1</span><span>2</span>').addClass('2');

Which should turn the html into this: 哪个应该把html变成这样:

   <div id="stuff">
    <span class="2">1</span><span class="2">2</span><span>3</span>
    </div>

However, the above does not work. 但是,上述方法不起作用。 Anyone know how to use jQuery to select things directly off the DOM by looking for the html? 任何人都知道如何使用jQuery通过查找html直接从DOM中选择内容吗?

Also, the span's must be selected in order, so if I had this: 另外,必须按顺序选择跨度,所以如果我有这个:

<div id="stuff">
<span>2</span><span>3</span><span>1</span>
</div>

And used the above JS, it would not do anything. 并使用了上面的JS,它什么也没做。

使用$( '#stuff span:not(:contains(3))' ).addClass( '2' )

right, if you want to look for various contents, do this: 正确,如果要查找各种内容,请执行以下操作:

<html>
   <head>
          <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
          <script type="text/javascript">
          $(function(){
                 var contains = [ 1 , 2 , 6 , 7 , 8 ] ;
                 $.map ( contains, function ( i ) {
                        $ ( '#stuff span:contains("'+ i +'")' ).addClass ( '2' ) ;
                 } ) ;
          });
          </script>
   </head>
   <body>
          <div id="stuff">
                 <span>1</span>
                 <span>2</span>
                 <span>3</span>
                 <span>4</span>
                 <span>5</span>
                 <span>6</span>
                 <span>7</span>
                 <span>8</span>
          </div>
   </body>

The output: 输出:

<div id="stuff">
       <span class="2">1</span>
       <span class="2">2</span>
       <span>3</span>
       <span>4</span>
       <span>5</span>
       <span class="2">6</span>
       <span class="2">7</span>
       <span class="2">8</span>
</div>

You can use the :contains pseudo-class: 您可以使用:contains伪类:

$('#stuff span:contains(1), #stuff span:contains(2)').addClass('2');

http://jsfiddle.net/SJxTu/ http://jsfiddle.net/SJxTu/

I'm not totally clear on what your selection condition is, but you Could use the jquery filter method with a function to select the spans. 我不清楚您的选择条件是什么,但是您可以将jquery筛选器方法与函数一起使用以选择范围。

For example from the docs: 例如从文档:

$('li').filter(function(index) {
   return $('strong', this).length == 1;
}).css('background-color', 'red');

http://api.jquery.com/filter/ http://api.jquery.com/filter/

You would need to check if $(this).text() === whatever 您将需要检查$(this).text()===

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

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