我对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");
});
据我所知,我的代码没有任何问题;所以我的问题是,由于按钮/链接节点是动态加载的,我无法绑定到它?谢谢你的帮助。
答案 0 :(得分:2)
是的,您需要使用委托。试试这个:
$(document).on('click','#button_notes', function() {
alert("ok");
});
来自jQuery documentation:
从jQuery 1.7开始,.on()方法是将事件处理程序附加到文档的首选方法。 [...]事件处理程序仅绑定到当前选定的元素; 在您的代码拨打电话到.on()时,页面上必须存在
。
这意味着您需要将事件处理程序附加到现有元素,然后使用.on()