本文介绍了如何合并逻辑或与逻辑与一个jQuery属性选择器内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下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>

使用jQuery,有没有办法选择谁是男性,是用户无论是从CA或NV,但不使用过滤器功能?需要明确的是,我知道

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

选择无论从CA或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());
});

谢谢!

推荐答案

试试这个:

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

基本上你链上的状态属性在一个单一的简单的选择(这将是你的逻辑与),一旦赘述每状态(这将是你的逻辑OR)。

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).

测试:

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

输出:

Max - CA
Bob - NV
Jon - CA

这篇关于如何合并逻辑或与逻辑与一个jQuery属性选择器内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 21:04