[英]How do I handle the event of an element getting added to the page?
I have an app where clicking a link brings up a modal. 我有一个应用程序,单击链接即可显示模式。 In the modal is a form. 在情态中是一种形式。 I need to monitor for that form's submission. 我需要监视该表单的提交。
I'm attaching a click handler in my JS like so: 我在JS中附加了点击处理程序,如下所示:
$('.vex-dialog-form :submit').click (event) ->
alert "hi"
That alert isn't firing, I believe it's because I need to attach some kind of event handler for that modal loading then put the submit event inside of that. 该警报不会触发,我相信是因为我需要为该模式加载附加某种事件处理程序,然后将Submit事件放入其中。
Any suggestions on how to go about this? 关于如何进行此操作有什么建议吗?
you need event delegation
for dynamically added DOM. 您需要event delegation
才能动态添加DOM。 use .on()
: 使用.on()
:
$('.vex-dialog-form').on('click',':submit',function(){
alert("hi");
});
if parent .vex-dialog-form
is also getting added dynamically, then use: 如果父.vex-dialog-form
也被动态添加,则使用:
$(document).on('click','.vex-dialog-form :submit',function(){
alert("hi");
});
Try this way: 尝试这种方式:
$(document).on('click', '.vex-dialog-form :submit', function(){
alert('hi');
});
In this case document
is waiting for click and after it gets clicked, jQuery finds out whether your submit button is clicked or not 在这种情况下, document
正在等待单击,并且在单击之后,jQuery会查找是否单击了提交按钮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.