javascript - 我可以绑定(bind)到使用 jquery.load() 加载的元素吗?

标签 javascript jquery html dynamic

我是 JQuery 的新手,所以如果这是一个愚蠢的问题,我很抱歉。

我用这行代码将 html 加载到一个 div 中:

$('#add_notes').load('index.php?route=module/notes/insert&token=<?php echo $token; ?>&customer_id=<?php echo $customer_id; ?>');

加载的文件包含下面列出的按钮/链接:

<a id="button_notes" class="button"><?php echo $button_add_note; ?></a>

一切都按应有的方式显示,但是我正在尝试使用以下语法将点击监听器附加到主文件中的按钮/链接:

$('#button_notes').bind('click', function() {
    alert("ok");

});

据我所知,我的代码没有任何问题;所以我的问题是,因为按钮/链接节点是动态加载的,所以我不能绑定(bind)到它吗?感谢您的帮助。

最佳答案

是的,你需要使用委托(delegate)。试试这个:

$(document).on('click','#button_notes', function() {
    alert("ok");
});

来自 jQuery documentation :

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. [...] Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

这意味着您需要将事件处理程序附加到现有元素,然后使用 .on() 进行委托(delegate)

关于javascript - 我可以绑定(bind)到使用 jquery.load() 加载的元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21069318/

相关文章:

jquery - Vimeo 覆盖在悬停时永久删除

jquery - jqgrid - 水平滚动条 - 位置 - 分页后 - 从左到右

javascript - 有没有办法只获取顶部元素的outerHTML?

javascript - 在php中提交html表单

JavaScript/HTML Canvas : clearing a text box

javascript - meteor mup 设置 mongo 失败 sudo : command not found

html - Css 边框为 :hover element

javascript - 将 HTML5 集成到 native iPad 应用程序中

javascript - Rails 部分模态(从不同模型渲染部分)

javascript - 使用 JavaScript 变量