2016-03-08 66 views
-1

我有20個div,每一個speficif類,所以我選擇它,並檢查是否是4'特殊'的1。Javascript多個語句在一個單一的,如果不工作

的主要問題是,下面的代碼應該工作...

$('.cbp-ig-grid li, .cbp-ig-grid li a span object').on('click', function() { 
     /* Variables Definition */ 
     var item = $(this).find('span').attr('class').split(' ')[1] 
} 


    if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4')){ 


// Always enters here! 

}else{ 

    // Never enters here :( (I need to enter here for the 4 cases in the if statement) 

    } 

但是當我只是一個做...它的作品!

if(item != 'item1'){ 


// do stuff 

}else{ 

    // do other stuff 

    } 

我不知道我做錯了,請幫忙將是有益的

+1

是的,它可能是,但它需要把它作爲變量ble,而不是再次選擇:/ –

+0

除此之外,你的Javascript看起來不是有效的。找到你的物品後,丟失一個''''並且移除''''。 – NiZa

+0

對不起,我會編輯帖子(除了真碼以外,很快) –

回答

2

考慮您的if語句:

if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4')){ 

} 

那是什麼要說的是,如果有任何的這些條件是真實的,if條件得到滿足並且它將執行if塊。

假設該項目是"item2"現在您的if語句的第一個表達式得到滿足,因爲它不是item1,因此該部分爲真。因此它執行該塊。 你想要的是:& &

if((item != 'item1') && (item != 'item2') && (item != 'item3') && (item != 'item4')){ 
    //when it's not the special case. 
} 
else 
{ 
    //the 4 special cases. 
} 
+2

是的,所以根據他的代碼示例,這是正確的,否則就會發生這種情況。 「/ /永遠不會進入:(:(我需要在這裏輸入4例在if語句)」 – JanR

+0

是的,你是對的,我錯過了,所以我刪除了我的評論 – godzsa

2
if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4')){ 

沒有機會進入人在這裏...... item總是從一個或另一個不同。

2

.hasClass()是你最好的朋友。 https://api.jquery.com/hasclass/

$('.cbp-ig-grid li, .cbp-ig-grid li a span object').on('click', function() { 
    /* Variables Definition */ 
    var item = $(this).find('span'); 

    switch(true) { 
     case item.hasClass('item1'): 
      // item 1 
     break; 

     case item.hasClass('item2'): 
      // item 2 
     break; 

     case item.hasClass('item3'): 
      // item 3 
     break; 

     case item.hasClass('item4'): 
      // item 4 
     break; 

     default: 
      // other stuff 
    } 
}); 
1

讓我們把它簡單

if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4')) 

測試一下:

1:

item = 'item1': 
false || true || true || true 
that equals to true; because false || true = true 

2:

item = 'theGreatOldOnes' 
true || true || true || true - that equal to true 

兩者都是真的!這意味着,你的表達是有缺陷的 - 它不會使「專班」和任何「非特殊類」之間的區別

爲了使理解的差異「特殊」和「無特殊」你需要使用:

if((item != 'item1') && (item != 'item2') && (item != 'item3') && (item != 'item4')) 

或者

if((item === 'item1') || (item === 'item2') || (item === 'item3') || (item === 'item4')) 

你可以測試與「物品1」和「theGreatOldOnes」,以獲得關於這些事情更好的抓地力^^

相關問題