【问题标题】:dynamic checkbox insertion, jquery onchange event lost动态复选框插入,jquery onchange 事件丢失
【发布时间】:2012-03-27 13:33:01
【问题描述】:

我有以下几点:

一些文件.php

$("document").ready(function() {  
    var handler = function(data) {  
    var JsDiv = document.getElementById("somediv");
    JsDiv.innerHTML = data;
  };

$("input[type='checkbox']").change( function() {
    console.log("execute lots of code in this function");
    //I need to execute this part again with the new checkboxes
    //.
    //.
    //.
    //and then
$.ajax({
        url: "ajaxFile.php",
        success: function(data, textStatus, XMLHttpRequest) { handler(data); }
});

  });
});

<div id="somediv">
<input type="checkbox" id="someid1" value="anything1" /> checkbox1
<input type="checkbox" id="someid2" value="anything2" /> checkbox2
</div>


ajaxFile.php
echo "
<input type='checkbox' id='someid3' value='anything3' /> checkbox3 <br />
<input type='checkbox' id='someid4' value='anything4' /> checkbox4
";


问题是 $("input[type='checkbox']").change(function() {}) 在我第一次加载页面时执行得很好,但是一旦通过 ajax 加载了新的复选框,它们不受该函数的约束。我见过有关 bind() 和 live() 的事情,但我不太明白如何将新复选框绑定到我已经定义的函数。我需要执行 .change() 内部的一些代码。我会在 .change() 之外提取该代码,然后调用该函数,但我不太确定该怎么做。

如果我的问题不清楚,请告诉我,我会重新措辞。感谢您的帮助。

【问题讨论】:

    标签: jquery ajax dynamic checkbox insert


    【解决方案1】:

    您只需要委托给不会被破坏的祖先侦听器。下面的 sn-p 使用 .on() 和委托语法,可以替代您的 .change() 事件监听器。

    $("#someContainer").on("change", "input[type='checkbox']", function() {
      console.log("execute lots of code in this function");
    });
    

    someContainer 显然(我希望)是一个占位符名称。它只是意味着围绕目标输入的任何容器。尽力确定最近的祖先,因为这将具有最大的性能优势。但如果你绝对必须,你总是可以使用文档:

    $(document).on("change" /* .....etc.... */);
    

    【讨论】:

    • 但是如何导出与 console.log("execute many code in this function"); 相同位置的代码是这样我可以重复使用它而不是两次编写相同的函数。
    • 更新了答案以提供对评论的回复
    • 这行得通,但是我如何获得我单击的实际复选框元素而不是整个容器。函数中的“this”给了我整个容器,而不是我点击的元素。
    • 嗯,这行得通:$("#secondBody input[type=\'checkbox\']").live("change", "input[type=\'checkbox\']", function () {
    • 那你错过了什么。在我的函数中,this 是被点击的元素。见jsfiddle.net/S8rbh。此外,live 已被弃用,您不应该使用它。最后,这不是live 的正确语法,所以我对它为什么起作用感到困惑。 ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多