【问题标题】:Using jQuery selectors to get form elements based on value or state使用 jQuery 选择器根据值或状态获取表单元素
【发布时间】:2009-11-16 23:47:01
【问题描述】:

我们 jQuery 是否可以根据表单元素的值和/或状态来选择表单元素的集合?

例如,我有一些看起来像这样的代码

jQuery("input[type='checkbox']").each(function(element){
    if(this.checked)
    {
         //do something with the checked checkeboxes
    }
});

我想删除内部条件,并以某种方式将其添加到初始选择中。作为选择器字符串的一部分,或者通过链上的一些附加方法调用。

【问题讨论】:

    标签: jquery html forms


    【解决方案1】:

    专门针对checked属性,可以使用:checked选择器:

    var checkedInputs = $('input:checked');
    

    对于其他属性,您可以使用attribute filters

    【讨论】:

      【解决方案2】:

      对于任意过滤,也可以使用filter(正如@CMS 建议的那样)。类似于 grep,但专门用于 jQuery 选择集。

      jQuery("input[type='checkbox']")
          .filter(function(){ return this.checked; })
          .each(function() {
              // Do something with "this"
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-24
        • 2011-12-07
        相关资源
        最近更新 更多