我在使用详细信息和摘要标签的巨大“类似索引”文件中计算儿童数时遇到问题。需要知道特定摘要标签有多少个孩子。代码示例只有完整文件的一小部分,但它显示了我正在寻找的内容:我使用“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>