multiple selectors jquery

不想你离开。 提交于 2019-12-24 01:53:30

问题


This:

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

will select a checkbox with the class of people and the name toddS while unchecking all of the other boxes.

How do I add another name to the filter? I've tried several different combinations and nothing works. This is what I have:

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

回答1:


You can pass a function into .attr(), like this:

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

If you need to add more later, you can use something that works for more values, for instance $.inArray(), like this:

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



回答2:


You could use a function there to select the ones you want only.

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

I also used removeAttr() instead of setting it to false. I haven't checked what jQuery does by setting it to false, but from a HTML perspective, being unchecked should mean the absence of that attribute.



来源:https://stackoverflow.com/questions/3489809/multiple-selectors-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!