【问题标题】:JQuery .on() binding does not work after part of page is reloaded重新加载部分页面后,JQuery .on() 绑定不起作用
【发布时间】: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


【解决方案1】:
$('#reloadable').on('click','.supplimentalButton',function(){
    alert($(this).val());
});

$('#mainButton').on('click', function(){
    $('#reloadable').html('<input type="button" class="supplimentalButton" value="Alert does not work anymore" />')
});

给你:http://jsfiddle.net/4JEQv/5/

【讨论】:

  • 成功了!谢谢。如此简单,不敢相信我在阅读文档后还没有尝试过。
【解决方案2】:

使用事件委托

$('#reloadable').on('click','.supplimentalButton',function(){
    alert($(this).val());
});

【讨论】:

  • 成功了!谢谢。很简单!不敢相信我在看完文档后还没有尝试过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-07
  • 1970-01-01
  • 2017-11-03
相关资源
最近更新 更多