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();
});
});
});
});
精彩评论