問題描述
給定以下 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']")
只選擇男性用戶,而
$(xml).find("user[state='CA'],[state='NV']")
從 CA 或 NV 中選擇所有用戶.但我無法在單個選擇器中將它們與邏輯 AND 結合起來.
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']")
基本上,您將 sex
和 state
屬性鏈接在一個簡單的選擇器中(這將是您的邏輯與),并在每個狀態重復一次(這將是你的邏輯或).
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 屬性選擇器中將邏輯 OR 與邏輯 AND 結合起來?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!