2011-02-18 82 views
0

所以,我有一些人工複選框(所以我可以設計他們的樣子),使用jQuery作爲選中或不選中。有一些我的文檔中的虛假的複選框,併爲每一個我有一個點擊功能:jQuery if(x == y)not working

var productInterest = []; 
productInterest[0] = false; 
productInterest[1] = false; 
productInterest[2] = false; 

// here is one function of the three: 

$('#productOne').click(function() { 
    if (productInterest[0] == false) { 
     $(this).addClass("checkboxChecked"); 
     productInterest[0] = true; 
    } else { 
     $(this).removeClass("checkboxChecked"); 
     productInterest[0] = false; 
    } 
}); 

這個問題似乎是有if語句的錯誤,因爲它會檢查,但不取消選中。換句話說,它會添加類,但變量不會改變,所以它仍然認爲它被檢查。任何人有任何想法?謝謝你的幫助。因此,我需要向您展示我的所有代碼,因爲它以我提供的方式工作(感謝評論者幫助我認識到這一點)......只是不以它實際上用於我的方式現場。所以請在下面找到完整的代碼。

所有事情都需要在一個函數中發生,因爲每個複選框的UI和數據需要一次更新。因此,這裏是完整的功能:

$('input[name=silkInterest]').click(function() { // they all have the same name 

    var silkInterest = []; 
    silkInterest[0] = false; 
    silkInterest[1] = false; 
    silkInterest[2] = false; 

    if ($(this).is('#silkSilk')) { // function stops working because the .is() 
     if (silkInterest[0] == false) { 
      $(this).addClass("checkboxChecked"); 
      silkInterest[0] = true; 
     } else { 
      $(this).removeClass("checkboxChecked"); 
      silkInterest[0] = false; 
     } 
     alert(silkInterest[0]); 
    } 
    if ($(this).is('#silkAlmond')) { 
     if (silkInterest[1] == false) { 
      $(this).addClass("checkboxChecked"); 
      silkInterest[1] = true; 
     } else { 
      $(this).removeClass("checkboxChecked"); 
      silkInterest[1] = false; 
     } 
    } 
    if ($(this).is('#silkCoconut')) { 
     if (silkInterest[2] == false) { 
      $(this).addClass("checkboxChecked"); 
      silkInterest[2] = true; 
     } else { 
      $(this).removeClass("checkboxChecked"); 
      silkInterest[2] = false; 
     } 
    } 

    var silkInterestString = silkInterest.toString(); 
    $('input[name=silkInterestAnswer]').val(silkInterestString); 
    // This last bit puts the code into a hidden field so I can capture it with php. 

}); 
+0

你的代碼適合我。 (雖然你真的應該使用循環,而不是複製粘貼3次) – david 2011-02-18 04:24:07

+0

在點擊事件觸發後嘗試提醒值,看它是否實際上已被更改。 – JohnP 2011-02-18 04:26:09

回答

0

好吧,剛剛有額頭一刻。關於我修改後的代碼 - 每次點擊時變量都會重置。這是問題所在。咄。

3

我不能當場在你的代碼的問題,但你可以簡單地使用你的地方productInterest陣列的添加類。這使您可以凝聚的代碼到一個單一:

// Condense productOne, productTwo, etc... 
$('[id^="product"]').click(function() { 
    // Condense addClass, removeClass 
    $(this).toggleClass('checkboxChecked'); 
}); 

並檢查其中的一個檢查:

if ($('#productOne').hasClass('checkboxChecked')) {...} 

這將確保用戶界面總是同步到「數據」 ,所以如果有其他代碼干擾你會發現它。