开发者

jquery to get last highlighted element value

开发者 https://www.devze.com 2023-04-05 00:12 出处:网络
I have a number of list items called selectedli h开发者_Python百科aving with the css background-color: #efefef;

I have a number of list items called selectedli h开发者_Python百科aving with the css background-color: #efefef;

I want to get the value of the last highlighted list item that has the selectedli class applied to it.

This is my code...

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    $('#btnSelect').click(function() {
        alert( $('#wrapper').find('li').filter("[class=leaf]").last().text() ); //bingo
        alert( $('#wrapper').find('li').hasClass('selectedli').last().text() ); //fail to get value when the class got 2 value inside...
        alert( $('#wrapper').find('li').filter('selectedli').last().text() ); //fail to get value when the class got 2 value inside...
        alert($('#wrapper').find('li .selectedli').last().text());
    });
</script>

<div id="wrapper">
    <div id="panel" class="cats1">
        <ul id="list_items">
            <li class="root" data-category_id="1">Fashion</li>
            <li class="root selectedli" data-category_id="2">Computer</li>
        </ul>
    </div>
    <div id="panel" class="cats1">
        <ul id="list_items">
            <li class="root" data-category_id="5">Laptop</li>
            <li class="root selectedli" data-category_id="6">Monitor</li>
        </ul>
    </div>
    <div id="panel" class="cats1">
        <ul id="list_items">
            <li class="leaf" data-category_id="13">LCD Dell</li>
            <li class="leaf selectedli" data-category_id="14">LCD Acer</li>
        </ul>
    </div>
</div>

<input type="button" id="btnSelect" value="Select">

I can't seem to get my code to work. Could someone please assist me to fix the problem.


Try this:

$("#list_items .selectedli").last().data("category_id");

DEMO (updated): http://jsfiddle.net/ugdYm/1/


One more suggestion, don't use jQuery 1.5 This version has issues.


Just do $("#list_items li.selectedli").last().attr("data-category_id");

update: was missing last()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号