我有一个元素列表:
<ul id="wpsl-stores">
<li>list</li>
<li>list</li>
<li class="skipthis">list</li>
<li>list</li>
<li>list</li>
<li>list</li>
<li class="skipthis">list</li>
<li>list</li>
</ul>
我正在循环遍历元素并附加该元素的编号:
var locCount = $('#wpsl-stores li').length;
for (i = 1; i < locCount+1; i++) {
$('#wpsl-stores ul li:nth-child('+i+') strong:before').hide();
$('body').append('<style>#wpsl-stores ul li:nth-child('+i+') strong:before {content:"'+i+'";}</style>');
}
我需要跳过具有“skipthis”类的元素。
在实际站点上,具有“skipthis”类的元素被隐藏,但仍在 dom 中。这意味着上面的循环仍在对它们进行计数。
现在,输出是这样的:
1 列表
2 列表
4 列表
5 list
6 列表
ETC。
等等
我需要它
1 列表
2 列表
3 列表
4 列表
最佳答案
您应该选择所有不跳过的元素并循环添加:
$('#wpsl-stores li:not(.skipthis)').each(function(i,li) {
$('body').append('<style>#wpsl-stores ul li:nth-child('+(i+1)+') strong:before {content:"'+(i+1)+'";}</style>');
});
编辑: 如果您想删除skipthis并为其他添加一个计数器:
var listCount = 0;
$('#wpsl-stores li').each(function(i,li) {
if ($(this).hasClass('skipthis')) {
$(this).remove();
} else {
listCount++;
$('body').append('<style>#wpsl-stores ul li:nth-child('+listCount+') strong:before {content:"'+listCount+'";}</style>');
}
});
关于javascript - 如何在 jQuery for 循环中跳过特定类的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48571290/