How do I combine logical OR with logical AND within a jQuery attribute selector?

自闭症网瘾萝莉.ら 提交于 2019-12-18 13:14:13

问题


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']");


来源:https://stackoverflow.com/questions/4404995/how-do-i-combine-logical-or-with-logical-and-within-a-jquery-attribute-selector

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