2016-06-15 73 views
1

我試圖建立一個基於多個條件的過濾器,我想結合數據和CSS屬性。jQuery - 在多個條件下過濾

例如: 我有多個DIV的數據屬性被稱爲「數據組」,在共享相同數據組值的DIV中,我想定位具有相對定位的DIV。

<div id="a" data-group="1" style="position:fixed"> 
<div id="b" data-group="1" style="position:relative"> 
<div id="c" data-group="1" style="position:fixed"> 
<div id="d" data-group="0" style="position:fixed"> 

我想創建數據組= 1和固定位置的所有DIV的過濾器分組。

當我只有一個條件,我傾向於使用如下:

common = $("div").filter(function() { return $(this).attr("data-group") === 1;   }); 

...但我怎麼可以申請第二個條件?

謝謝!

洛朗

回答

2

過濾fixed

common = $("div").filter(function() { 
    return $(this).attr("data-group") === 1 && $(this).css('position') === 'fixed'; 
}); 

過濾relative

common = $("div").filter(function() { 
    return $(this).attr("data-group") === 1 && $(this).css('position') === 'relative'; 
}); 
+0

簡單而優雅,這就是我喜歡的,謝謝! – Laurent

4

你可以做到這一點類似於你現在正在做的方式:

common = $("div").filter(function() { 
    return $(this).attr("data-group") == 1 && this.style.position == 'fixed' ; 
}); 

或用一行代碼:

common = $('div[data-group="1"][style="position:fixed"]'); 
+0

謝謝,我標記了第一個帖子的正確答案,但你的答案同樣好。對於這一行,它是否也適用於在css而不是inline中設置的位置? – Laurent

+1

不,因爲你需要JavaScript和'getComputedStyle' – j08691