我正在努力解决我最近的代码中发生的奇怪问题。
我有一个动态生成的列表,其中每行都包含一个复选框。 我的意图是,如果复选框发生变化并且我得到确认,我的数据库将被更新。
问题是,我第一次改变时它确实有效。但以下尝试却没有。 但如果我刷新页面,它会在我第一次更改时再次工作。
它必须是一些 JavaScript 的东西。
$(':checkbox').change(function() {
if (confirm("Does the status of this survey really changed?")) {
variable = $(this).val();
$.post( "handler.php", { handler: '18', value: variable}, location.reload());
}
});
PS:每次触发“变量”并且值发生变化时也会发出警报。
各位能帮我解决一下吗?
提前致谢。
编辑:非常感谢您的所有回答。 除了对事件委托(delegate)的理解之外,对我有帮助的是它与点击事件配合得更好。我仍然会尝试理解在 onblur 触发 onchange 的意义是什么,但目前,保持 onchange 对我没有帮助。
最佳答案
正如您所提到的,行是动态生成的,您需要使用 event delegation像这样:
$(document.body).on("change",":checkbox", function() {
if (confirm("Does the status of this survey really changed?")) {
variable = $(this).val();
$.post( "handler.php", { handler: '18', value: variable}, location.reload());
}
});
其中 $(document.body)
或 $(document)
是目标元素的容器,您可以使用最接近的父元素/容器而不是 $(document.body)
或 $(document)
.
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
关于javascript - jquery 复选框 onchange 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23763196/