我知道如何选择包含某个字符串的元素,但是如何选择具有某个类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' );
答案 0 :(得分:0)
你的语法不是很正确。您需要将:contains
放在选择器的字符串中,并将my_string
值连接到它。试试这个:
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;
更新
鉴于您更新的HTML和JS示例,问题是由于选择器中的空格。这应该有效:
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;