Javascript 复选框onchange jquery出现问题

Javascript 复选框onchange jquery出现问题,javascript,jquery,checkbox,onchange,Javascript,Jquery,Checkbox,Onchange,我最近的代码中发生了一个奇怪的事情,这让我很为难 我有一个动态生成的列表,其中每行包含一个复选框。 我的意图是,如果复选框更改,并且我得到确认,我的数据库将被更新 问题是,我第一次换衣服的时候,它确实起作用了。但是下面的尝试没有。 但是如果我刷新了页面,它会在我第一次更改时再次工作 它必须是一些javascript的东西 $(':checkbox').change(function() { if (confirm("Does the status of this survey reall

我最近的代码中发生了一个奇怪的事情,这让我很为难

我有一个动态生成的列表,其中每行包含一个复选框。 我的意图是,如果复选框更改,并且我得到确认,我的数据库将被更新

问题是,我第一次换衣服的时候,它确实起作用了。但是下面的尝试没有。 但是如果我刷新了页面,它会在我第一次更改时再次工作

它必须是一些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:每次触发“变量”且值发生变化时,也会发出警报

你们能帮我解决这个问题吗

提前谢谢

编辑:非常感谢所有的答案。
除了了解活动代表团之外,帮助我的是,它与click event一起工作得更好。我仍将尝试理解在onblur触发onchange的意义,但目前,保留onchange对我没有帮助。

对于动态创建的DOM元素:

$(':checkbox').on("change",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).on("change", ":checkbox" ,function() { // you can replace with wrapping container ID
    if (confirm("Does the status of this survey really changed?")) {
        variable = $(this).val();
        $.post( "handler.php", { handler: '18', value: variable}, location.reload());
    }
});
您必须在较新版本中使用事件

比如说

$(':checkbox').live('change', 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).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

事件委派允许我们将单个事件侦听器附加到父元素,该事件侦听器将为与选择器匹配的所有子体触发,无论这些子体现在存在还是将来添加

使用$input:checkbox工作小提琴:


根据Jquery,您应该使用$input:checkbox

为什么不使用onclick?@Alek为什么OP应该使用onclick???@A.Wolff显然,Alek从一开始就是正确的。谢谢兄弟!不,对于jquery1.9+,live已经死了。在委托语法上,或者对于较旧的jQuery版本,使用委托,这比live要好。我知道,我更新了我的答案。可能他使用的是旧版本^^我在更新我的评论。在所有情况下,不要使用livedocument类型的元素,document是一个对象。因此,$'document'返回空的jQuery对象在这里,您的选择器将针对具有类body的document类型的元素,您希望改为:$document.body或$'body'或真正将其委托给未注册DOM ready或未注册的:$document我接受这一点是因为有这样的解释,但真正的问题是onchange如何工作。
 $(document).ready(function(){
   $('input:checkbox').change(function() {
      if (confirm("Does the status of this survey really changed?")) {
          variable = $(this).val();
          alert(variable);
        }
    });
 });