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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6120943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:26:03  来源:igfitidea点击:

Why is this jQuery ajax click event firing multiple times?

jqueryajax

提问by Chris Dowdeswell

I have tried unbinding the click event, but it fires sometimes twice sometimes 5 times!! Getting a bit fed up now!

我试过取消绑定点击事件,但它有时会触发两次有时会触发 5 次!!现在有点腻了!

Code from modal.asp

代码来自 modal.asp

$("input[name=add_associate]").live("click",function(){
    var addassociateID = $(this).attr("id")

    $.ajax({
       type: 'POST',
       url: '/data/watchlist_save.asp',
       data: {m : 'share_watchlist_add', watchListID : <%=WatchListID%>, a : addassociateID},
       async:true,
       success: function(data) {
           $(".associate_users").load("/data/sub_watch_members.asp?watchListID=<%=WatchListID%>",
           {cache:false},function() {
               $(".search_note").html(data)         
               $(this).unbind('click').bind('click',handler);                                                                                                
           })
       },
       error: function(data){
           $(".search_note").html(data)
       }
    });     
})

UPDATE:
Basically I am calling the following code into .associate_users

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

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

FURTHER INFORMATION:
This only happens when I fire the event, close the modal dialog then re-open it with a different watchListID

进一步信息
这只发生在我触发事件,关闭模态对话框然后用不同的watchListID

THE STRUCTURE OF DATA:

数据结构:

  • main.asp: LOADS >
  • modal.asp: modal.asp contains the jquery from above + two divs on this page with panel1.asp and panel2.asp data...
  • panel1.asp: Contains the HTML above...
  • panel2.asp: Contains nothing related... just pure HTML.
  • main.asp: 负载 >
  • modal.asp: modal.asp 包含上面的 jquery + 此页面上的两个 div 以及 panel1.asp 和 panel2.asp 数据...
  • panel1.asp: 包含上面的 HTML...
  • panel2.asp:不包含任何相关内容...只是纯 HTML。

采纳答案by Chris Dowdeswell

I have resolved this issue now, I was using

我现在已经解决了这个问题,我正在使用

$(document).ready

in the loaded ajax content along with...

在加载的ajax内容中......

<script src="/js/jquery-ui.js"></script>

So I presume it was doubling up the "live" function!

所以我认为它是“实时”功能的两倍!

Thank you so much for the responses.

非常感谢您的答复。

回答by DarthJDG

Watch your semicolons, make sure you end each command with one, will save you a headache later.

注意你的分号,确保每个命令都以一个结尾,这样以后你就不会头疼了。

As for events bound by live(), they have to be unbound by calling die(). It has the same parameters as unbind(). Have a look at the documentation.

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

function ajaxHandler(){
    var addassociateID = $(this).attr("id");
    var $this = $(this);
    $this.die('click');

    $.ajax({
        type: 'POST',
        url: '/data/watchlist_save.asp',
        data: {m : 'share_watchlist_add', watchListID : <%=WatchListID%>, a : addassociateID},
        async: true,
        success: function(data) {
            $(".associate_users").load("/data/sub_watch_members.asp?watchListID=<%=WatchListID%>",{cache:false},function(){
                $(".search_note").html(data);
                $this.bind('click',handler);
            });
        },
        error: function(data){
            $(".search_note").html(data);
            $this.live('click', ajaxHandler);
        }
    });     
}

$("input[name=add_associate]").live("click", ajaxHandler);

Edit:Forgot to add some important points. You have to unbind your live event right in the click handler and rebind it on error, just like @stefansuggested.

编辑:忘记添加一些要点。你必须在点击处理程序中取消绑定你的实时事件,并在出错时重新绑定它,就像@stefan建议的那样。

Also make sure you save the thisobject in a variable, as it's not pointing to your DOM element within the ajax callback function. Alternatively you can use the contextproperty on your ajax request, check the documentation.

还要确保将this对象保存在变量中,因为它没有指向 ajax 回调函数中的 DOM 元素。或者,您可以context在 ajax 请求中使用该属性,请查看文档

回答by Rajesh

As I see, all you want to do is bind the event once and then die it. The latest jQuery versions have a .one() method, which will bind the event only once.

如我所见,您要做的就是绑定事件一次,然后将其终止。最新的 jQuery 版本有一个 .one() 方法,它只会绑定一次事件。

example:

例子:

$('#myDiv').one('click', function() {
    alert('clicked once...');
});

The next time you click, click event will not fire up.

下次单击时,单击事件不会触发。

More at http://api.jquery.com/one/

更多信息请访问http://api.jquery.com/one/

回答by Elliot Nelson

You can fix your problem in two ways:

您可以通过两种方式解决您的问题:

1) Move your javascript code into main.asp, instead of modal.asp.

1) 将您的 javascript 代码移动到 main.asp,而不是 modal.asp。

This will instantly fix your double-fire issue. You would have to modify your code slightly to pull the WatchListID value from some HTML inside modal.asp, rather than coding it directly as you are (since main.asp won't have that value yet.)

这将立即解决您的双发问题。您必须稍微修改您的代码以从 modal.asp 内的某些 HTML 中提取 WatchListID 值,而不是直接编码它(因为 main.asp 还没有那个值。)

2) Keep your javascript code where it is, but stop using live events.

2) 将您的 javascript 代码保留在原处,但停止使用实时事件。

Use a simple ".click(function () {" call, instead of ".live('click', function() {".

使用简单的“.click(function () {”调用,而不是“.live('click', function() {”。

You are reloading modal.asp each time the dialog opens, which means your javascript is being run every time it loads. If you keep your javascript code in modal.asp, then live() is probably not appropriate.

每次打开对话框时,您都在重新加载 modal.asp,这意味着您的 javascript 每次加载时都在运行。如果您将 javascript 代码保存在 modal.asp 中,那么 live() 可能不合适。

回答by stefan

You are unbinding first afterwards the success. You need to unbind it in the click handler and then add it again onerror.

成功后您先解除绑定。您需要在单击处理程序中解除绑定,然后在出错时再次添加它。

回答by KarasQ

I solved it like this:

我是这样解决的:

    var liveActionRemove = $('#ajax-list-action-remove');

    $(liveActionRemove).live('click', function(){
        $(liveActionRemove).die('click');

        $.ajax({
            url: '/someurl',
            success: function(data){
            }
        });
    });