2017-05-22 75 views
1

我想突出显示任何元素的类别以a_slot_开头,但不以任何类名称中的pink或​​结尾。在这个例子中,我觉得应该突出显示第三个元素,因为它的类别为a_slot_orange,另一个类别不包含pink或​​。jquery选择器缺失元素

为什么不突出显示第三个元素(但最后一个元素是)?我如何突出与其他人的第三?

$(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>

+3

第3段不a_slot_ – Gerard

+0

你可能想使用'$开始( “[*类= '_ a_slot']”)'。 – abhishekkannojia

+0

@Gerard我知道,但第二课确实 – depperm

回答

1

当你使用:

$("[class^='a_slot_']") 

您只选择元素开始a_slot_,但第三个元素是开始a_slot(不包括以下_)。

对于您应该使用$("[class*='a_slot_']")

1

可以使用jQuery.filter

$("[class^='a_slot']").filter(
    function(){ 
     var matches = $(this).attr('class').match(/pink|green/g); 
      return !matches; 
    } 
).css('background-color', 'red'); 

啊,是因为别人指出你的选择是太贪婪我已经删除了下划线

https://jsfiddle.net/py89zr5y/1/

0

让它变成这样,因为^表示字符串的开始。

<p class='a_slot_orange a_slot'>Orange (shouldn't I be highlighed too?)</p> 
2

与您选择[class^='a_slot_']你只选择其阶级属性与该字符串开始的元素,所以你不会选择前三个元素,所以你可以改变,要[class^='a_slot']之后,你可以为每个元素拆分类属性和使用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>

+0

您也可以使用两个属性选择器,这可能更高效(可以移植到CSS)。看到重复的链接。 – BoltClock