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

前端 未结 2 1635
醉酒成梦
醉酒成梦 2020-12-31 17:23

Given the following XML:


    Max
    Jen
    &l         


        
相关标签:
2条回答
  • 2020-12-31 17:30

    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
    
    0 讨论(0)
  • 2020-12-31 17:52

    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']");
    
    0 讨论(0)
提交回复
热议问题