好的,所以我有一个基本的复选框列表,如下所示:
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="lowercase" id="lowercase" checked="true"> lowercase letters
</label>
<label class="checkbox">
<input type="checkbox" name="uppercase" id="uppercase"> UPPERCASE LETTERS
</label>
<label class="checkbox">
<input type="checkbox" name="digits" id="digits"> Digits 0 to 9
</label>
<label class="checkbox">
<input type="checkbox" name="symbols" id="symbols"> Punctuation / Symbols <small>(e.g. % $ & * ! ... ) </small>
</label>
<label class="checkbox">
<input type="checkbox" name="ascii" id="ascii"> All ASCII Characters
</label>
</div>
</div>
当选中每个复选框时,它所在的表单将通过 ajax 提交到 calc.php。如果复选框被选中,计算的一部分使用我分配的值,如下所示:
if (isset($_POST['lowercase'])) {
$numChars += 26;
}
if (isset($_POST['uppercase'])) {
$numChars += 26;
}
if (isset($_POST['digits'])) {
$numChars += 10;
}
if (isset($_POST['symbols'])) {
$numChars += 12;
}
if (isset($_POST['ascii'])) {
$numChars = 96;
}
因此,正如您将看到的,如果用户选择了多个复选框,它会将相应的值加到 var numChars 中。如果用户选择“所有 ASCII”,那么 var 应该有一个固定值 96,因为这是我感兴趣的可用 ascii 字符的数量。我使用这个论坛上其他地方找到的代码来删除另一个检查如果勾选了“ascii”框。
$(function () {
var el = $('input:checkbox');
el.on('change', function (e) {
if ($(this).attr('id') != 'ascii') {
if ($(this).is(':checked'))
$('#ascii').prop('checked', false);
else {
var l = $(':checkbox')
.filter(':checked')
.not('#ascii').length;
if (l == 0)
$('#ascii').prop('checked', true);
}
} else {
if ($(this).is(':checked'))
el.not($(this)).prop('checked', false);
}
});
});
一切正常。除了一部分。如果我选择“小写”,则 numChars 为 26。如果我随后选择“大写”,则 numChars 正确地为 52。等等。如果我选择“ascii”,则 numChars 变为 96。但如果我选择其他任何内容,如“大写”numChars尽管屏幕上的复选框更新,但仍保持在 96。它只会在我选择“ascii”后发生,所以无论我在它之后按什么,都需要再次点击才能更新 numChars 的值。
希望这是有道理的。我试图制作一个 jsfiddle,但尽管阅读了/echo/html 示例,但还是在 ajax 方面苦苦挣扎。:-)
最佳答案
根据您的要求,您必须将操作代码更改为:
$numChars = 0;
if (isset($_POST['ascii'])) {
$numChars = 96;
}
else
{
if (isset($_POST['lowercase'])) {
$numChars += 26;
}
if (isset($_POST['uppercase'])) {
$numChars += 26;
}
if (isset($_POST['digits'])) {
$numChars += 10;
}
if (isset($_POST['symbols'])) {
$numChars += 12;
}
}
关于javascript - 选择复选框后变量未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20610188/