jquery:选择内容的最后一个元素

时间:2014-11-26 06:13:51

标签: javascript jquery html css

在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>

2 个答案:

答案 0 :(得分:3)

在jquery中使用 contains() last() 选择器

$( "ul li:contains('bar'):last" ).css("color","red");

<强> DEMO

答案 1 :(得分:2)

您有几个选择:

&#13;
&#13;
// :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;
&#13;
&#13;

虽然请记住:contains() 不精确

&#13;
&#13;
// :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;
&#13;
&#13;

或者:

&#13;
&#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;
&#13;
&#13;

参考文献: