jquery如何从数组值中过滤元素

时间:2013-06-27 08:00:11

标签: jquery filter

在我的表单中,我应该根据数组中的存在应用两个类的类,以便我如何过滤?

这是我的尝试:

<form>

    <input type="checkbox" value="one" />
    <input type="checkbox" value="two" />
    <input type="checkbox" value="three" />
    <input type="checkbox" value="four" />
    <input type="checkbox" value="five" />

</form>

var names = ["one","two","three"];


$(":checkbox", "form").filter(function(){
    return $(this).val() === names
}).addClass("blue")

$(":checkbox", "form").filter(function(){
    return $(this).val() !== names
}).addClass("green")

但不起作用..任何正确的方法来完成它

here is the fiddle

1 个答案:

答案 0 :(得分:3)

您需要检查数组中是否存在输入值,而不是数组名称是否等于该值。为此您可以使用$.inArray,如果它在数组中找到它,它将返回该项的索引 - >

$("form :checkbox").filter(function(){
    return $.inArray(this.value, names) > -1
}).addClass("blue")

$("form :checkbox").filter(function(){
    return $.inArray(this.value, names) == -1
}).addClass("green")

演示:Fiddle

或者

var names = ["one","two","three"];

$("form :checkbox").addClass(function(){
    return $.inArray(this.value, names) > -1 ? 'blue' : 'green'
})

演示:Fiddle