【问题标题】:multiple selectors jquery多个选择器 jquery
【发布时间】:2011-03-30 05:20:34
【问题描述】:

这个:

$('input.people').attr('checked', false).filter('[name=toddS]').attr('checked', true);

将选择一个带有人员类别和名称 toddS 的复选框,同时取消选中所有其他框。

如何向过滤器添加其他名称?我尝试了几种不同的组合,但没有任何效果。这就是我所拥有的:

$('input.people').attr('checked', false).filter('[name=toddS], [name=gwenD]').attr('checked', true);

【问题讨论】:

    标签: jquery checkbox filter jquery-selectors


    【解决方案1】:

    你可以use a function there选择你想要的。

    $('input.people')
       .removeAttr('checked')
       .filter(function() {
           return ($(this).attr('name') === 'toddS' || $(this).attr('name') === 'gwenD');
        })
        .attr('checked', 'checked');
    

    我还使用了removeAttr(),而不是将其设置为false。我还没有通过将 jQuery 设置为 false 来检查它的作用,但从 HTML 的角度来看,未选中应该意味着没有该属性。

    【讨论】:

      【解决方案2】:

      您可以将函数传递给.attr(),如下所示:

      $('input.people').attr('checked', function() {
        return this.name == 'toddS' || this.name == 'gwenD';
      });
      

      如果您以后需要添加更多,您可以使用适用于更多值的东西,例如$.inArray(),如下所示:

      $('input.people').attr('checked', function() {
        return $.inArray(this.name, ['toddS', 'gwenD']) != -1;
      });
      

      【讨论】:

      • 谢谢,尼克。现在,当取消选中 Todd 和 Gwen 的位置时,如何取消选中?
      • @sehummel65 - 你能澄清一下吗?我不明白这个问题......你想要相反,或者取消选中所有人或......?
      猜你喜欢
      • 2011-07-14
      • 2011-10-31
      • 2011-11-18
      • 2011-10-17
      • 2012-02-10
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      相关资源
      最近更新 更多