I have the follow html:
<ul id="myList">
<li>
<a class="myListItem li-selected">One</a>
</li>
<li>
<a class="myListItem">Two</a>
</li>
<li>
<a class="myListItem li-selected">Three</a>
</li>
<li>
<a class="myListItem">Four</a>
</li>
<li>
<a class="myListItem">Five</a>
</li>
</ul>
The li-selected class is added when the respective <li> tag is getting selected. I am trying in $(document).ready() to check if any of the li's is selected (having li-selected class). As a result I am expecting a boolean to use every time the page loads to pass it in an other function as a parameter.
I am trying something like this but it doesn't return true although it should:
$(document).ready(function() {
.
.
.
var hasSelectedItems = $("#myList li").find("a").hasClass("li-selected");
console.log(hasSelectedItems);
.
.
.
});
Expected result:
SOLVED
As it turned out there was nothing wrong with the way I was trying to check if the li-selected class existed but with the when I was trying to do it. I misplaced the var hasSelectedItems = $("#myList li").find("a").hasClass("li-selected");
part and tried to find a class that hadn't been added yet. So I moved that part of the code to run when the elements are rerendered after the addition of the li-selected class and it works.
Please use the following jquery code to find a
tag:
$(document).ready(function() {
var lis = $("#myList li a.li-selected").length;
if(lis > 0)
{
//code here
}
else
{
//empty
}
});
您可以找到选择了类 li 的锚元素的长度:
var lis = $("#myList li a.li-selected").length > 0 ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.