问题
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