为什么这个jQuery ajax点击事件多次触发?

前端之家收集整理的这篇文章主要介绍了为什么这个jQuery ajax点击事件多次触发?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经尝试解除绑定点击事件,但有时会有时两次触发5次!现在有点厌倦了!

来自modal.asp的代码

  1. $("input[name=add_associate]").live("click",function(){
  2. var addassociateID = $(this).attr("id")
  3.  
  4. $.ajax({
  5. type: 'POST',url: '/data/watchlist_save.asp',data: {m : 'share_watchlist_add',watchListID : <%=WatchListID%>,a : addassociateID},async:true,success: function(data) {
  6. $(".associate_users").load("/data/sub_watch_members.asp?watchListID=<%=WatchListID%>",{cache:false},function() {
  7. $(".search_note").html(data)
  8. $(this).unbind('click').bind('click',handler);
  9. })
  10. },error: function(data){
  11. $(".search_note").html(data)
  12. }
  13. });
  14. })

更新:
基本上我将以下代码调用到.associate_users中

  1. <div id="associate_list">
  2. <div class="associate_record">
  3. <div class="left" style="padding:8px;"><img src="../imgs/nopic-m.png" style="width:30px;height:30px;" class="img_border" /></div>
  4. <div class="left" style="padding-top:15px;">5)Neil Burton</div>
  5. <div class="right" style="padding-top:10px;margin-right:5px;"><input type="button" class="btn-blue" name="add_associate" id="890" value="Add"></div>
  6. <div style="clear:both;"></div>
  7. </div>
  8. <div style="clear:both;"></div>
  9. </div>

更多信息:
这只发生在我触发事件时,关闭模态对话框,然后用不同的watchListID重新打开它

数据结构:

> main.asp:LOADS>
> modal.asp:modal.asp包含该页面上面两个div的jquery,其中包含panel1.asp和panel2.asp数据…
> panel1.asp:包含上面的HTML …
> panel2.asp:没有任何相关的…只是纯HTML。

解决方法

注意你的分号,确保你用一个命令结束,稍后会让你头疼。

对于由live()绑定的事件,它们必须通过调用die()来解除绑定。它具有与unbind()相同的参数。看看documentation

  1. function ajaxHandler(){
  2. var addassociateID = $(this).attr("id");
  3. var $this = $(this);
  4. $this.die('click');
  5.  
  6. $.ajax({
  7. type: 'POST',async: true,success: function(data) {
  8. $(".associate_users").load("/data/sub_watch_members.asp?watchListID=<%=WatchListID%>",function(){
  9. $(".search_note").html(data);
  10. $this.bind('click',handler);
  11. });
  12. },error: function(data){
  13. $(".search_note").html(data);
  14. $this.live('click',ajaxHandler);
  15. }
  16. });
  17. }
  18.  
  19. $("input[name=add_associate]").live("click",ajaxHandler);

编辑:忘记添加重点。您必须在点击处理程序中解除直播活动,并将其重新绑定出错,就像@stefan建议一样。

还要确保将此对象保存在变量中,因为它不是指向ajax回调函数中的DOM元素。或者,您可以使用您的ajax请求的上下文属性,查看documentation

猜你在找的jQuery相关文章