简体   繁体   English

我怎样才能找到<a>一个特定的类,当它在</a><li>

[英]How can i find if an <a> has a specific class when it is in an <li>

I have the follow html:我有以下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. 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).我试图在$(document).ready()中检查是否选择了任何 li(具有li-selected类)。 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:我正在尝试这样的事情,但它不会返回true虽然它应该:

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

Expected result:预期结果:

  • hasSelectedItems === true then at least one <li> is selected. hasSelectedItems === true那么至少一个 <li> 被选中。
  • hasSelectedItems === false then no <li> is selected. hasSelectedItems === false那么没有 <li> 被选中。

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.事实证明,我尝试检查li-selected类是否存在的方式没有任何问题,但是当我尝试这样做时。 I misplaced the var hasSelectedItems = $("#myList li").find("a").hasClass("li-selected");我放错了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.因此,当添加li-selected类后重新渲染元素时,我将那部分代码移动到运行,并且它可以工作。

Please use the following jquery code to find a tag:请使用下面的jQuery代码找到a标签:

$(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 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM