jQuery:visible选择器无法提供正确的输出

时间:2018-10-02 08:35:21

标签: javascript jquery html

我正在尝试找到第一个“可见” li,在下面的代码中将是li2-2

但是出于某种原因,.children('li:visible').attr()给了我<li>中的第一个<ul>

我该如何解决?

alert($("#myul").children('li:visible').attr("id"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="descendants">body (great-grandparent)
  <div style="width:500px;">div (grandparent)
    <ul id="myul">ul (direct parent)  
      <li style="visibility:hidden;" id="li1-1">li (child)
        <span>span (grandchild)</span>
      </li>
      <li style="visibility:visible;" id="li2-2">li (child)
        <span>span (grandchild)</span>
      </li>
      <li style="visibility:hidden;" id="li3-3">li (child)
        <span>span (grandchild)</span>
      </li>
      <li style="visibility:visible;" id="li4-4">li (child)
        <span>span (grandchild)</span>
      </li>
    </ul>   
  </div>
</body>

3 个答案:

答案 0 :(得分:1)

  

jquery doc中提到的具有可见性:隐藏或不透明:0的元素被视为可见。

这会使您的代码选择所有li

您可以使用.filter()来过滤具有visibility:visible的元素

var id = $("#myul").children('li').filter(function(){
  return $(this).css("visibility") == "visible"
}).first().attr("id");
console.log(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:500px;">div (grandparent)
  <ul id="myul">ul (direct parent)  
    <li style="visibility:hidden;" id="li1-1">li (child)
      <span>span (grandchild)</span>
    </li>
    <li style="visibility:visible;" id="li2-2">li (child)
      <span>span (grandchild)</span>
    </li>
    <li style="visibility:hidden;" id="li3-3">li (child)
      <span>span (grandchild)</span>
    </li>
    <li style="visibility:visible;" id="li4-4">li (child)
      <span>span (grandchild)</span>
    </li>
  </ul>   
</div>

答案 1 :(得分:1)

您可以使用nth-child选择器选择特定的孩子

$(document).ready(function(){
    alert($("#myul li:nth-child(2):visible").attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:500px;">div (grandparent)
    <ul id="myul">ul (direct parent)  
      <li style="visibility:hidden;" id="li1-1">li (child)
        <span>span (grandchild)</span>
      </li>
      <li style="visibility:visible;" id="li2-2">li (child)
        <span>span (grandchild)</span>
      </li>
      <li style="visibility:hidden;" id="li3-3">li (child)
        <span>span (grandchild)</span>
      </li>
      <li style="visibility:visible;" id="li4-4">li (child)
        <span>span (grandchild)</span>
      </li>
    </ul>   
  </div>

答案 2 :(得分:1)

您可以通过以下方式使用它:

alert($("#myul").children('li[style="visibility:visible;"]').attr("id"));