我试图添加"禁用" class到一个类名不在数组中的元素,我有一个这样的数组输出:
["xs", "xl", "s", "m"]
和这样的html标记:
<a href="js:;" class="pa_size xs" title="xs" data-select="pa_size" data-value="xs">XS</a>
<a href="js:;" class="pa_size xl" title="xl" data-select="pa_size" data-value="xl">XL</a>
<a href="js:;" class="pa_size s" title="s" data-select="pa_size" data-value="s">S</a>
<a href="js:;" class="pa_size m" title="m" data-select="pa_size" data-value="m">M</a>
<a href="js:;" class="pa_size l" title="l" data-select="pa_size" data-value="l">L</a>
我尝试过这样的事情:
if ( $.inArray(val, array) !== -1 ) { ... }
或
$.each(array, function() { ... }
但没有运气。
答案 0 :(得分:3)
使用数组生成multiple class selector,并在jQuery中使用 :not()
伪类或 not()
方法避免使用它们。
var classes = ["xs", "xl", "s", "m"];
$('a').not(classes.map(function(v) {
// iterate and add `.` before each element
return '.' + v;
// join using `,` to act them as multi selector
}).join(',')).addClass('class')
&#13;
.class {
color: red
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="js:;" class="pa_size xs" title="xs" data-select="pa_size" data-value="xs">XS</a>
<a href="js:;" class="pa_size xl" title="xl" data-select="pa_size" data-value="xl">XL</a>
<a href="js:;" class="pa_size s" title="s" data-select="pa_size" data-value="s">S</a>
<a href="js:;" class="pa_size m" title="m" data-select="pa_size" data-value="m">M</a>
<a href="js:;" class="pa_size l" title="l" data-select="pa_size" data-value="l">L</a>
&#13;
或者更为简单 @charlietfl 建议
var classes = ["xs", "xl", "s", "m"];
$('a').not('.' + classes.join(',.')).addClass('class')
&#13;
.class {
color: red
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="js:;" class="pa_size xs" title="xs" data-select="pa_size" data-value="xs">XS</a>
<a href="js:;" class="pa_size xl" title="xl" data-select="pa_size" data-value="xl">XL</a>
<a href="js:;" class="pa_size s" title="s" data-select="pa_size" data-value="s">S</a>
<a href="js:;" class="pa_size m" title="m" data-select="pa_size" data-value="m">M</a>
<a href="js:;" class="pa_size l" title="l" data-select="pa_size" data-value="l">L</a>
&#13;