如果任何.block-badge的值为0,我在dom中有多个元素和.blockbadge类,那么我想在该元素中添加一个类,以便以不同的方式设置它.
我的JS将类添加到所有这些元素中,如果它们中的任何一个等于0.我如何使它只影响那些等于零的元素?
<span class="block-badge">1</span> <span class="block-badge">0</span> // this element should have the class 'zero' added <span class="block-badge">4</span>
JS
var blockBadgeVal = $('.block-badge').val(); if (blockBadgeVal < 0) { $('.block-badge').addClass('zero'); }
解决方法
OP中的代码不起作用,因为$(‘.block-badge’).html()将返回带有类块标记的第一个元素的html,所以在这种情况下返回字符串1,你应该解析返回的值然后将它与0进行比较.
Description: Reduce the set of matched elements to those that match the selector or pass the function’s test.
$('.block-badge').filter(function(){ return parseInt($(this).text())==0; }).addClass('zero');
希望这可以帮助.
$('.block-badge').filter(function(){ return parseInt($(this).text())==0; }).addClass('zero');
.zero{ color: red; font-weight: bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="block-badge">1</span> <span class="block-badge">0</span> <span class="block-badge">4</span>