如何找到<a> has a specific class when it is in an </a> <li> <a>

时间:2015-06-16 08:39:49

标签: javascript jquery html css backbone.js

I have the follow html:

<ul id="myList">
    <li>
        <a class="myListIntem-1 li-selected">One</a>
    </li>
    <li>
        <a class="myListIntem-1">Two</a>
    </li>
    <li>
        <a class="myListIntem-1 li-selected">Three</a>
    </li>
    <li>
        <a class="myListIntem-1">Four</a>
    </li>
    <li>
        <a class="myListIntem-1">Five</a>
    </li>
</ul>

The li-selected class is added when the "li a" is selected (when the user has clicked on it). I am trying in my $(document).ready(function() {}); to check if any of the li's is selected. In this case the first and the third are.

I want a boolean result because i want to use it every time the page loads.

I was trying something like this but it doesnt work:

$(document).ready(function() {
var lis = $("#myList li").find("a").hasClass("li-selected");
});

If lis is true then at least on li is selected. If lis is false then no li is selected.

Any ideas?? FYI:I am using backbone.js

2 个答案:

答案 0 :(得分:0)

请使用以下jquery代码查找a代码:

$(document).ready(function() {
    var lis = $("#myList li a.li-selected").length;
    if(lis > 0)
    {
     //code here
    }
    else
    {
     //empty
    }
});

答案 1 :(得分:-1)

您可以找到选择了类li的锚元素的长度:

var lis = $("#myList li a.li-selected").length > 0 ;