首页 > 解决方案 > jquery HTML5 细节和总结,计算孩子的问题

问题描述

我在使用详细信息和摘要标签的巨大“类似索引”文件中计算儿童数时遇到问题。需要知道特定摘要标签有多少个孩子。代码示例只有完整文件的一小部分,但它显示了我正在寻找的内容:我使用“href”值调用函数 getAnswer,该函数确实找到了正确的条目,但从那里我被卡住了:如何找出孩子的数量。注释掉的行表明我尝试了各种方法,但它们都给出了答案 0,所以我想我不能使用 $(this)。任何帮助表示赞赏!

getAnswer('2013'); // should be 4
getAnswer('2013_spring'); // should be 0
getAnswer('2013_summer'); // should be 0
getAnswer('2013_autumn'); // should be 3

function getAnswer(question) {
  var numChilds = $('summary a[href="' + question + '"]').length; // 1001
  if (numChilds == 1) { // then a summary record was found
    console.log('Found summary for ' + question);
    // console.log('Nr of children for ' + question + ': ' + $(this).parent("details").children().length); 	
    // console.log('Nr of children for ' + question + ': ' + $(this).parent("ul").children().length); 
    // console.log('Nr of children for ' + question + ': ' + $(this).parent("details > li").length); 
    // console.log('Nr of children for ' + question + ': ' + $(this).next("ul li").length); 
    // console.log('Nr of children for ' + question + ': ' + $(this).next("ul > li").length); 
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<ul>
  <details>
    <summary><a class="sitemap" href="2013">Year</a></summary>
    <ul>
      <li><a class="sitemap" href="2013_spring">Spring</a></li>
      <li><a class="sitemap" href="2013_summer">Summer</a></li>
      <ul>
        <details>
          <summary><a class="sitemap" href="2013_autumn">Autumn</a></summary>
          <ul>
            <li><a class="sitemap" href="apples">Delicious Apples</a></li>
            <li><a class="sitemap" href="bananas">Yellow Bananas</a></li>
            <li><a class="sitemap" href="cacao">Warm Chocolate</a></li>
          </ul>
        </details>
      </ul>
      <li><a class="sitemap" href="2013_winter">Winter</a></li>
    </ul>
  </details>
</ul>

标签: jquerychildrendetails-tagsummary-tag

解决方案


mplungjan 刷新了我对 $(this) 的使用方法的记忆后,得出的结论是肯定有更好更快的方法,所以过了一会儿我想出了下面的解决方案来查找孩子的数量,'属于'总结

var numChilds = $('summary a[href="' + question + '"]').parent().next().children().length;

获取“属于”摘要的孩子的数量并不像应有的那么直接,因为摘要本身“独立”,因此它没有孩子;孩子们属于ul这也是(作为摘要也是)细节的一部分。

上面的代码做了什么:它找到具有唯一 href 值的摘要“记录”,然后找到它的父级,即SUMMARY,您可以使用以下代码检查:

$('summary a[href="' + question + '"]').parent()[0].nodeName;

然后它找到summary的下一个兄弟,即ul(它们都是details的孩子,因此可以使用next )。对于这个ul,它会询问children的数量(.length)。因此,通过后退一步,然后前进两步,您可以获得孩子的数量。

希望这对某人有用。至少对我来说是这样。


推荐阅读