How do I combine logical OR with logical AND withi

2019-02-09 06:23发布

问题:

Given the following XML:

<users>
    <user state="CA" sex="m">Max</user>
    <user state="AZ" sex="f">Jen</user>
    <user state="OR" sex="f">Kim</user>
    <user state="NV" sex="m">Bob</user>
    <user state="CA" sex="m">Jon</user>
    <user state="AZ" sex="m">Jim</user>
    <user state="OR" sex="f">Joy</user>
    <user state="NV" sex="f">Amy</user>
</users>

Using jQuery, is there a way to select users who are male and are either from CA or NV, but without using the filter function? To be clear, I know that

$(xml).find("user[sex='m']")

selects only male users, while

$(xml).find("user[state='CA'],[state='NV']")

selects all users from either CA or NV. But I am not able to combine both of them with a logical AND within a single selector.

Using the filter function, however, the following works:

$(xml).find("user").filter(function() {
    return $(this).attr('sex') == 'm' && ($(this).attr('state') == 'CA' || $(this).attr('state') == 'NV')
}).each(function() {
    alert($(this).text());
});

Thanks!

回答1:

Try this:

$(xml).find("user[sex='m'][state='CA'], user[sex='m'][state='NV']")

Basically you chain the sex and state attributes together in a single simple selector (this would be your logical AND), and repeat them once per state (and this would be your logical OR).

Test:

$(xml).find("user[sex='m'][state='CA'], user[sex='m'][state='NV']")
      .each(function() {
          alert($(this).text() + " - " + $(this).attr('state'));
      });

Output:

Max - CA
Bob - NV
Jon - CA


回答2:

You can combine multiple selectors, but your syntax isn't exactly correct:

$(xml).find("user[state='CA'],[state='NV']")

This finds all <user> elements with the state "CA" and any other nodes (not necessarily <user>) with state "NV". What you want is:

$(xml).find("user[state=CA][sex=m],user[state=NV][sex=m]")

If you don't want to repeat yourself:

$(xml).find("user").filter("[state='CA'],[state='NV']").filter("[sex='m']");