Why is this jQuery ajax click event firing multiple times?

后端 未结 7 1874
无人共我
无人共我 2020-12-14 08:13

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

Code from modal.asp

$         


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 09:01

    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.

    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 @stefan suggested.

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

提交回复
热议问题