[英]jQuery if (x == y) not working
因此,我有一些偽造的復選框(以便為它們設置樣式),這些復選框可與jQuery一起使用,以充當已選中或未選中狀態。 我的文檔中有許多人造復選框,每一個都有一個單擊功能:
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.
});
我無法在您的代碼中發現問題,但是您可以簡單地使用要添加的類代替productInterest
數組。 這使您可以將代碼壓縮為單個代碼:
// Condense productOne, productTwo, etc...
$('[id^="product"]').click(function() {
// Condense addClass, removeClass
$(this).toggleClass('checkboxChecked');
});
並檢查是否其中之一被選中:
if ($('#productOne').hasClass('checkboxChecked')) {...}
這樣可以確保UI始終與“數據”同步,因此,如果有其他代碼在干擾您,您將可以發現它。
好吧,只是手掌到額頭的瞬間。 關於我修改后的代碼-每次單擊都會重置變量。 那就是問題所在。 咄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.