【问题标题】:jQuery to hide a DIV if it has no unordered list items如果 DIV 没有无序列表项,jQuery 将隐藏它
【发布时间】:2012-02-05 15:01:52
【问题描述】:

如果不存在无序列表项,我很难想出一个 div 的所有内容的 jQuery 脚本。所以如果 div 里面有无序列表项,那么 div 就会被显示,否则会被隐藏。

这是我必须测试的基本 html:

<html>
<title>Experiment Fix Div Hidding</title
<head>

<link rel="stylesheet" type="text/css" href="css/css.css" media="all"/>
<script src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>

</head>

<body>

<table>

<tr>
<td>
<div id="contenFirst">Sample Content. Not display if not bullets points exists
<ul>
<li><a href="#">Hello world</a></li>
<li><a href="#">Hello world2</a></li></ul></div>
</td>
</tr>

</table>

</body>
</html>

这是我到目前为止想出的脚本,但它似乎没有完成这项工作:

$(document).ready(function(){

// hiding a div based on it not having any content (unordered list items)
if($("#contentFirst").html().length == 0){
$("#contentFirst").hide();
} 
});

我使用 jquery 脚本的方式是正确的,以前对 jquery 做的不多。

任何建议将不胜感激。

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    如果您的 div 没有任何无序列表,这将返回 true:

    if($("#contentFirst ul").length == 0){
    

    此外,如果您想简单地隐藏没有 ul 的 div,您可以执行以下操作:

    $("#contentFirst:not(:has(ul))").hide();
    

    【讨论】:

      【解决方案2】:

      试试这个:

      $(document).ready(function() {
          $('#contentFirst').hide();
          $('#contentFirst').has('ul').show();
      });
      

      【讨论】:

      • 感谢安德鲁成功了。感谢大家的建议,所有有用的地方。
      【解决方案3】:

      首先,您可能有错字:)

      <div id="contenFirst">Sample Content. Not display if not bullets points exists
      <ul>
      

      您的contentFirst 缺少一个“t”。

      其次,您要计算&lt;li&gt; 列表项,但contentFirst 的直接子级是永远不会消失的&lt;ul&gt;,因此contentFirst 将始终有内容。

      你可以这样做:

      if($("#contentFirst").find("li").length === 0){
          $("#contentFirst").hide();
      } 
      

      find() 将返回所有 &lt;li&gt; 项,即使它们不是直系子项!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多