复选框onchange jquery发出问题

时间:2014-05-20 14:52:28

标签: javascript jquery checkbox onchange

我在最近的代码中遇到了一些奇怪的事情。

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

问题是,它在我第一次改变时确实有效。但以下尝试没有。 但是,如果我刷新页面,它会在我第一次更改时再次起作用。

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

你能帮我解决一下吗?

提前致谢。

编辑:非常感谢所有答案。 除了对事件委托的理解之外,帮助我的是,它对点击事件的效果更好。我仍然会试着理解在onblur触发onchange的重点是什么,但目前,保持onchange并没有帮助我。

4 个答案:

答案 0 :(得分:9)

正如您已经提到动态生成行,您需要使用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) OR $(document)是目标元素的容器,您可以使用最接近的父元素/容器而不是$(document.body)$(document)

  

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

答案 1 :(得分:0)

对于动态创建的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());
    }
});

答案 2 :(得分:0)

您必须使用.live()个事件(在较新版本.on()中)

例如

$(':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());
    }
});

答案 3 :(得分:0)

使用$( "input:checkbox" ) 工作小提琴http://jsfiddle.net/h3ar8/

 $(document).ready(function(){
   $('input:checkbox').change(function() {
      if (confirm("Does the status of this survey really changed?")) {
          variable = $(this).val();
          alert(variable);
        }
    });
 });

根据Jquery http://api.jquery.com/checkbox-selector/你应该使用$( "input:checkbox" )

相关问题