2016-06-15 75 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