【问题标题】:jquery how to filter a element from array valuejquery如何从数组值中过滤元素
【发布时间】:2013-06-27 08:00:11
【问题描述】:

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

这是我的尝试:

<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

【问题讨论】:

    标签: jquery filter


    【解决方案1】:

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

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

    【讨论】:

    • 没有投反对票,但为什么不使用names.indexOf(this.value)
    • @JanDvorak 对 IE 的支持
    猜你喜欢
    • 2014-02-11
    • 2012-09-17
    • 2018-05-24
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 2023-03-26
    • 2020-12-20
    • 2022-01-03
    相关资源
    最近更新 更多