jQuery bind 事件不会在通过 $().load() 加载的元素上触发

jQuery bind event not firing on elements loaded via $().load()

本文关键字:加载 load 元素 事件 bind jQuery      更新时间:2023-09-26

我有一个 DIV 位于一个 .html 文件中,该文件通过以下方式加载到我的文档中:

$(document).Ready( function() {
    $("#contentDiv").load("some.html")

    //some.html contains a button id=saveButton
    $("#saveButton").click( function () {
        alert("Here I am!");
    }
});

事件不会触发。 如果我剪切一些内容.html并将其放在文档中,嗯,"物理上",事件将触发。

所以,我很确定这个问题与通过 .load() 注入 html 的事实有关。

这很麻烦,因为如果你查看页面源代码,所有的HTML实际上都在那里,包括按钮。

所以,问题是,有没有办法做到这一点? 我正在使用 .load() 来降低页面复杂性并提高可读性,而且,尽管有代码折叠,但我真的不想将所有这些 HTML 拉入文档中。

编辑:此代码只是即兴输入的。 这不是实际代码的切入,只是为了演示问题所在。 但是,感谢您指出这一点。

编辑2:Grrrrrrr。 });

load() 是异步的,所以你需要在回调中完成作业:

$(document).ready(function() {
    $("#contentDiv").load("some.html", function(){
        //some.html contains a button id=saveButton
        $("#saveButton").click( function () {
            alert("Here I am!");
        });
    });
});

希望对:)有所帮助

一种方法是在 some 中添加脚本行.html该脚本行将在div 出现时加载。

您可以将此脚本添加到某些.html(在脚本标记中):

registerButton();

然后,您可以在当前文档中定义 registerButton()。

另一种方式,如果我没记错的话,是使用类似函数 bind( )

的东西
如果你想

在 DOM 准备就绪时不可用的元素上触发事件,那么你需要使用 .on 事件。

http://api.jquery.com/on/

$("#saveButton").on("click", function() {
      alert("Here I am!");
});

jquery load() 函数是异步的。如果要将事件绑定到加载的内容,则应将代码放入回调函数中:

$(document).ready(function() {
    $("#contentDiv").load("some.html", function() {
        //you should put here your event handler
    });
});

你的问题是 jquery load() 函数是异步的,正如@lucas提到的。但是他的代码有语法错误,试试这个:

    $(document).ready(function () {
        $("#contentDiv").load("some.html", function () {
            $("#saveButton").click(function () {
                alert("Here I am!");
            });
        });
    });

希望现在有帮助

您需要

在加载后将事件处理程序绑定到加载中的 HTML 容器

$(document).ready(function() {
  $("#contentDiv").load("some.html", function() {
    $("#saveButton").on('click',function() {
      alert("Here I am! Bound in callback");
    });
  });
});

或使用:(不需要它在文档中准备好,只需contentDiv存在)

$("#contentDiv").on('click','#saveButton',function(){
     alert("Here I am! bound to container div");
});

编辑:加载保存按钮单击(每条评论)(虽然这没有意义)

$(document).ready(function() {
  $("#saveButton").on('click',function() {
    $("#contentDiv").load("some.html", function() {
      alert("Here I am! Bound in callback");
    });
  });
});