【发布时间】:2013-11-25 15:23:09
【问题描述】:
在我的页面上,我有一个用于报告的过滤器表单。表单是通过 ajax 提交的,然后我重新加载页面的一部分。页面部分重新加载后,jQuery 绑定不再在页面的重新加载部分中起作用。
这是我的html:
<input type="button" id="mainButton" value="Reload the container"/>
<div id="reloadable" style="border: 1px solid black;">
<input type="button" class="supplimentalButton" value="You should see alert" />
</div>
这是 jQuery 1.9.1 绑定:
// this bit works just fine first time.
// but after reload the binding is no longer attached
// and alert is not coming up on button click
$('.supplimentalButton').on('click',function(){
alert($(this).val());
});
// this is what reloads the container
$('#mainButton').on('click', function(){
$('#reloadable').html('<input type="button" class="supplimentalButton" value="Alert does not work anymore" />');
});
这里是 jsFiddle:http://jsfiddle.net/trailmax/4JEQv/4/
到目前为止,我看到的所有建议都是使用.on() 绑定。这就是我正在做的事情。对这个问题有什么建议吗?
【问题讨论】:
-
因为绑定事件时元素不存在!阅读documentation of
on(),它解释了它。 -
@epascarello 是的,这就是我使用
.on()的原因 - 这是文档中建议的用途之一。 -
您是否阅读了文档中的"Direct and delegated events" 部分?用一个例子来解释这一切。
-
我确实浏览了..应该在那里多加注意-)
标签: javascript jquery html binding