选择某个类的元素,该元素也包含某个字符串

时间:2016-08-19 10:10:49

标签: jquery

我知道如何选择包含某个字符串的元素,但是如何选择具有某个类my_class 包含某个字符串my_string的元素?

$( '.myclass':contains(my_string) )之类的东西,除了当然没有效果。

HTML:

<div class='sheet_today'>
  <div class='person'>
    PERSON: <span class='sheet_today_person_name'>Kevin</span>
  </div>
  <div class='parent'>
    PARENT: <span class='sheet_today_parent_name'>Ron</span>
  </div>
</div>

<div class='sheet'>
  <div class='person'>
    PERSON: <span class='person_name'>Ron</span>
  </div>
  <div class='parent'>
    PARENT: <span class='parent_name'>Daniel</span>
  </div>
</div>
<div class='sheet'>
  <div class='person'>
    PERSON: <span class='person_name'>Raph</span>
  </div>
  <div class='parent'>
    PARENT: <span class='parent_name'>Mark</span>
  </div>
</div>
<div class='sheet'>
  <div class='person'>
    PERSON: <span class='person_name'>Mark</span>
  </div>
  <div class='parent'>
    PARENT: <span class='parent_name'>Tom</span>
  </div>
</div>
<div class='sheet'>
  <div class='person'>
    PERSON: <span class='person_name'>Daniel</span>
  </div>
  <div class='parent'>
    PARENT: <span class='parent_name'>Raph</span>
  </div>
</div>

JS:     var today_parent_name = $(&#39; .sheet_today_parent_name&#39;)。text();     $(&#39; .person_name:包含(&#34;&#39; + today_parent_name +&#39;&#34;)&#39;)。css(&#39;背景&#39;,&# 39;红色&#39;);

也尝试过:

$( '.person_name' ).find( ":contains('today_parent_name')" ).css( 'background', 'red' );

1 个答案:

答案 0 :(得分:0)

你的语法不是很正确。您需要将:contains放在选择器的字符串中,并将my_string值连接到它。试试这个:

&#13;
&#13;
var my_string = 'foo';
$('.myclass:contains("' + my_string + '")').addClass('foo');
&#13;
.foo {
  color: #C00;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclass">Lorem ipsum</div>
<div class="myclass">foo bar</div>
<div class="myclass">Dolor sit</div>
&#13;
&#13;
&#13;

更新

鉴于您更新的HTML和JS示例,问题是由于选择器中的空格。这应该有效:

&#13;
&#13;
var today_parent_name = 'Ron';
$('.person_name:contains("' + today_parent_name + '")').css('background', 'red');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='sheet' id='sheet001'>
  <div class='person'>
    PERSON: <span class='person_name'>Ron</span>
  </div>
  <div class='parent'>
    PARENT: <span class='parent_name'>Daniel</span>
  </div>
</div>
<div class='sheet' id='sheet002'>
  <div class='person'>
    PERSON: <span class='person_name'>Raph</span>
  </div>
  <div class='parent'>
    PARENT: <span class='parent_name'>Mark</span>
  </div>
</div>
<div class='sheet' id='sheet003'>
  <div class='person'>
    PERSON: <span class='person_name'>Mark</span>
  </div>
  <div class='parent'>
    PARENT: <span class='parent_name'>Tom</span>
  </div>
</div>
<div class='sheet' id='sheet004'>
  <div class='person'>
    PERSON: <span class='person_name'>Daniel</span>
  </div>
  <div class='parent'>
    PARENT: <span class='parent_name'>Raph</span>
  </div>
</div>
&#13;
&#13;
&#13;