在jquery中,如何在以下HTML中选择包含<li>
字符串的最后一个bar
:
<ul>
<li>bar</li>
<li>foo</li>
<li>foo</li>
<li>bar</li> <!-- I want to select this one -->
<li>foo</li>
</ul>
答案 0 :(得分:3)
在jquery中使用 contains() 和 last() 选择器
$( "ul li:contains('bar'):last" ).css("color","red");
<强> DEMO 强>
答案 1 :(得分:2)
您有几个选择:
// :contains(bar) would match 'bar', 'barbell' and 'rebar':
$('li:contains(bar)').last().css('color','red');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>bar</li>
<li>foo</li>
<li>foo</li>
<li>bar</li> <!-- I want to select this one -->
<li>foo</li>
</ul>
&#13;
虽然请记住:contains()
不精确:
// :contains(bar) would match 'bar', 'barbell' and 'rebar':
$('li:contains(bar)').last().css('color','red');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>bar</li>
<li>foo</li>
<li>foo</li>
<li>bar</li> <!-- I want to select this one -->
<li>barbell</li>
</ul>
&#13;
或者:
$('li').filter(function () {
// this retains only those <li> elements whose text is exactly equal to 'bar':
return $(this).text() === 'bar';
// selects the last of the elements from the collection:
}).last().css('color','red');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>bar</li>
<li>foo</li>
<li>foo</li>
<li>bar</li> <!-- I want to select this one -->
<li>foo</li>
</ul>
&#13;
参考文献: