2010-11-02 53 views
4

只是想弄清楚你怎么能这样jQuery OR Selector?

if (!(jQuery('#selector1 || #selector2').hasClass('some-class'))) { 
//code here 
} 

这不起作用现有的代码,即中测试多种选择,但不知道是否有什么我可以做,使工作?

回答

12

只需选择他们两个,如果其中一方有类some-class,条件为真:

if (!jQuery('#selector1, #selector2').hasClass('some-class')) { 
    //code here 
} 

或者,如果我误解你的逻辑,你可以(而且应该,速度和简单起见)打破这些成两个:

if (!(jQuery('#selector1').hasClass('some-class') || jQuery('#selector2').hasClass('some-class'))) { 
    //code here 
} 
+0

非常感谢 - 是的,你添加的第二位代码是我以后。谢谢 – Tom 2010-11-02 17:13:27

+0

查看我的答案,以减肥版... – hunter 2010-11-02 17:15:38

+0

@ hunter - 你的答案是不正确的,你正在检查后裔的类(它效率低得多)。 – 2010-11-02 17:16:20

0
if ((!('#selector1').hasClass('some-class')) || (!('#selector2').hasClass('some-class'))) { 
//code here 
} 

为什么不这样呢?

1

相当简单,它是一个逗号;)

if (!(jQuery('#selector1 .some-class, #selector2 .some-class'))) { 
//code here 
} 
1

不,我知道的。也许只是做这样的事情:

if((!$('#selectorid1').hasClass(class)) || (!$('#selectorid2').hasClass(class))){}