开发者

jQuery click event - first click makes ajax call, following clicks toggle

开发者 https://www.devze.com 2023-03-26 06:49 出处:网络
I have an anchor that when clicked makes an ajax call to load some html into a div and then load a script. I want to unbind that event after the first click, and replace it with another click event th

I have an anchor that when clicked makes an ajax call to load some html into a div and then load a script. I want to unbind that event after the first click, and replace it with another click event that toggles between showing and hiding that 开发者_如何学Godiv. I've got this far, but none of my attempts to register the click event that toggles the div work.

$('#anchor').click( function() {
    $('#div').load('file.html', function() {    
        $.getScript('script.js');       
        $('#anchor').unbind();
    });
});


$('#anchor').click( function(e) {
    e.preventDefault(); // prevent the browsers following the link
    $('#div').load('file.html', function() {    

        // make sure to bind once the new script has been included
        // i.e. within .getScript's callback
        $.getScript('script.js', function() {
            $('#anchor').unbind("click").click(myShowHideFunc);
        });       
    });
});


Try this with event namespace which help to unbind only the current event handler so that other click handlers are not touched when we unbind.

$('#anchor').click('click.anchor', function() {

    $('#div').load('file.html', function() {    
        $.getScript('script.js', function(){       
          $('#anchor').unbind('click.anchor').click(function(){
             $('#div').toggle();
          });
        });
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消