在HTML文档中使用JavaScript/JQuery的头标记之前计算具有特定类的div



我在JS/jQuery中写了一个脚本,在我的HTML文档中查找h1、h2和h3标记。如果脚本找到一个头标记,它会自动将标记的内容写入我的HTML文档。到目前为止,一切都很顺利,但我在下面的任务中遇到了一些问题。

假设我在HTML代码的第90行中有一个h1标记。目标是扩展JS脚本,以便它统计在h1标记之前出现的具有某个类的div的所有次数。

示例:

HTML:
<div class="example"></div>
<div class="example2"></div> <!--Should not count this one-->
<div class="example"></div>
<div class="example"></div>
<div class="example2"></div> <!--Should not count this one-->
<div class="example"></div>
<h1>TEST</h1>
<div class="example"></div>
<div class="example"></div>
<h2>TEST2</h2>
JS-Script:
1. Spots h1-tag in line 7 of the HTML-code and saves the value 4 in a variable because there were 4
divs with the class "example" before the spotted h1-tag
2. Spots h2-tag in line 10 of the HTML-code and saves the value 6 in the same variable because there
were 6 divs with the class "example" before the spotted h2-tag

到目前为止,我对JS代码应该是什么样子一无所知。

我希望你能理解这个问题,并知道帮助我的方法

如果按下h1或h2重置计数器,您可以在dom元素上循环并检查nodeName属性。更新:重读这个问题后,我意识到你不想重置每个header标签的计数器。。我删除了重置计数的代码。

let count = 0;
$('div,h1,h2,h3', 'body').each(function(){
const node = $(this).prop('nodeName');
if(['H1','H2'].includes(node)){
console.log(`${count} example div's before spotting ${node} tag`);
} else if($(this).hasClass('example')) {
count++;
}
});
console.log(`${count} example div's`);

最新更新