所以,我有一些人造复选框(这样我可以设计它们的样式),它们与 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 始终与“数据”同步,因此如果有其他代码干扰,您将能够发现它。
关于javascript - jQuery if (x == y) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5037548/