繁体   English   中英

jQuery绑定事件无法在通过$()。load()加载的元素上触发

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

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

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


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

});

该事件不会触发。 如果我将some.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出现时加载。

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

registerButton();

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

换句话说,如果我没记错的话,是使用诸如bind()之类的函数

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

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

});

如果您想对DOM准备就绪时尚不可用的元素触发事件,则需要使用.on事件。

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

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

您的问题是,如@lucas所述 ,jquery load()函数是异步的。 但是他的代码有语法错误,请尝试以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM