问题描述
我正在将一个'password-reset-success-message'div动态加载到'password-reset'div中,如下面的代码片段所示。'password-reset-success-message'div隐藏
$(#password)被覆盖到'password-reset'div中,如下所示。 -reset )HTML($( #密码重置成功 - 消息)HTML())。
现在'password-reset-success-message'div有一个'btnPasswordResetOK'按钮,它会关闭密码重置模式对话框。但此click()事件未绑定。我没有收到警报消息。
$(document).ready(function(){
$(#btnPasswordResetOK)。click(function(){
alert();
});
});
注意:但是没有答案。
更新:我用隐藏的div更新html后绑定,它工作! ,
$ b
$(#password-reset)。html($(#password-reset-success- 。消息)的html());
$ b $(#btnPasswordResetOK)。click(function(){
alert();
});
将它委托给您要添加html的父元素到
如果在.on()中使用jQuery 1.7+
$ p $ $(#password-reset)。on('click','#btnPasswordResetOK',function(){
})
使用委托
$(#password-reset)。委托('#btnPasswordResetOK','点击',函数(){
})
从使用哪种方法的jQuery文档中获得
$ b
通过委托,您可以将事件处理程序绑定到静态父元素,该元素不会更改并存在于绑定的时间。您指定要监听的元素和事件,当事件冒起时,它将由静态父元素处理。
I am loading a 'password-reset-success-message' div into a 'password-reset' div dynamically as shown in the below snippet.The 'password-reset-success-message' div is hidden on page load and is overwritten to the 'password-reset' div as shown below.
$("#password-reset").html($("#password-reset-success-message").html());
Now the 'password-reset-success-message' div has a 'btnPasswordResetOK' button which will close the password reset modal dialog.But this click() event is not getting binded. I am not getting the alert message. I am doing all of this wrapped inside the document ready.
$(document).ready(function(){
$("#btnPasswordResetOK").click(function() {
alert();
});
});
Note: This question is almost similar to my question..but there are not answers for it.
UPDATE : I binded after updating the html with the hidden div and it works ! , code snippet below
$("#password-reset").html($("#password-reset-success-message").html());
$("#btnPasswordResetOK").click(function() {
alert();
});
delegate it to the parent element you are adding the html to
if using jQuery 1.7+ with .on()
$("#password-reset").on('click','#btnPasswordResetOK',function(){
})
with delegate
$("#password-reset").delegate('#btnPasswordResetOK','click',function(){
})
From jQuery docs on which method to use
By delegating, you bind the event handler to a static parent element that doesn't change and exists at the time of binding. You specify the element and the events you want to listen to, and when the event bubbles up it will get handled by the static parent element.
这篇关于jquery点击事件不会触发先前隐藏的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!