This question already has answers here:
jQuery selector to target any class name (of multiple present) starting with a prefix?
(4个答案)
2年前关闭。
我想突出显示任何具有以
为什么第三个元素没有突出显示(而最后一个是突出显示)?如何与其他人一起突出显示第三个?
(4个答案)
2年前关闭。
我想突出显示任何具有以
a_slot_
开头但没有以任何类名以pink
或green
结尾的类的元素。在此示例中,我想强调的第三个元素是因为它具有类a_slot_orange
,而另一个类不包含pink
或green
。为什么第三个元素没有突出显示(而最后一个是突出显示)?如何与其他人一起突出显示第三个?
$(document).ready(function() {
$("[class^='a_slot_']").each(function(i,v){
if(!$(this).attr('class').includes('green') && !$(this).attr('class').includes('pink')){
$(this).css('background-color', 'red');
}
});
// also don't work....have the same result
//$("[class^='a_slot_']:not([class$='green'],[class$='pink'])").css('background-color', 'red');
//$("[class^='a_slot_']").not("[class$='green'],[class$='pink']").css('background-color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='a_slot a_slot_green'>Green</p>
<p class='a_slot a_slot_pink'>Pink</p>
<p class='a_slot a_slot_orange'>Orange (shouldn't I be highlighed too?)</p>
<p class='a_slot_green'>Green</p>
<p class='a_slot_pink'>Pink</p>
<p class='a_slot_orange'>Orange</p>
<p class='a_slot_4'>4</p>
<p class='a_slot_16'>16</p>
<p class='a_slot_16 other_class'>16</p>
<p class='a_slot_orange other_class'>Orange</p>
最佳答案
使用选择器[class^='a_slot_']
,您只能选择其class属性以该字符串开头的元素,因此您将不会选择前三个元素,因此可以将其更改为[class^='a_slot']
,然后您可以为每个元素拆分class属性,并使用some()
找到匹配。
$("[class^='a_slot']").each(function(i, v) {
var cls = $(this).attr('class').split(' ')
var check = cls.some(function(e) {
return e.startsWith('a_slot_') && !e.endsWith('green') && !e.endsWith('pink')
})
if (check) $(this).css('background', 'red')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='a_slot a_slot_green'>Green</p>
<p class='a_slot a_slot_pink'>Pink</p>
<p class='a_slot a_slot_orange'>Orange (shouldn't I be highlighed too?)</p>
<p class='a_slot_green'>Green</p>
<p class='a_slot_pink'>Pink</p>
<p class='a_slot_orange'>Orange</p>
<p class='a_slot_4'>4</p>
<p class='a_slot_16'>16</p>
<p class='a_slot_16 other_class'>16</p>
<p class='a_slot_orange other_class'>Orange</p>