jQuery bind 事件不会在通过 $().load() 加载的元素上触发
jQuery bind event not firing on elements loaded via $().load()
我有一个 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");
});
});
});
- .load()函数赢得't加载javascript
- 使用jquery.load('pageName')方法时,未从应用程序缓存加载Html页
- 使用.load()-jQuery缓慢加载内容
- 使用 jQuery .load() 加载的内容不起作用
- jquery .load() 不加载外部 JS
- j查询如何在加载了 load() 函数的页面上进行 POST/AJAX,而无需刷新页面
- .load() 事件在 SVG 完成加载后未被调用/无法访问其内容
- jQuery 不会使用 .load() 加载外部 html 模板
- jQuery UI不会加载到.button的$(“#content”).load页面上
- iFrame.load事件未等待预加载图像完成
- Yii ActiveForm:通过jQuery.load加载表单
- JQuery中的JQuery.load已加载页面/snippit
- 如何从使用jquery load()加载的另一个html页面执行在主html文件中编写的脚本
- 使用load()加载外部文件,然后使用fancybox插件进行修改并显示
- Eclipse Phonegap无法使用jquery.load函数加载外部字符串文件
- 如何使用JQuery.Load访问Div中加载URL的UL“id”,“name”等,以设置JQuery树视图
- JavaScript:从javascript加载图像,然后等待该图像的“load”事件
- 通过 .load() 加载的脚本失败
- jQuery .load:刷新页面时加载同一页面的任何方法
- 如何在 JS 中使用 .load 时显示“加载”动画