且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过JQuery加载和卸载JS文件的***方法

更新时间:2023-12-04 22:33:58

您无法卸载" JavaScript.一旦加载,就加载了.不能撤消.

You can't "unload" JavaScript. Once it's loaded, it's loaded. There's no undo.

但是,您可以分离事件处理程序.请参阅: http://api.jquery.com/unbind/

However, you can detach event handlers. See: http://api.jquery.com/unbind/

live()unbind()的特殊情况.实时事件处理程序是附加到document而不是元素上的,因此您必须像这样删除处理程序:

live() is a special case for unbind(), though. Live event handlers are attached to document rather than the element, so you have to remove the handler like so:

$(document).unbind('click');

但是,这可能会删除除相关问题之外的更多处理程序,因此您可以执行以下两项操作之一:1)命名处理程序函数或2)创建名称空间.

However, that would probably remove more handlers than just the one in question, so you can do one of two things: 1) name your handler function or 2) create a namespace.

命名处理程序功能

function myClickHandler(){
    var pl = $(this).attr('rel');
    $.getScript('' + siteAddress + 'min/?js=fjs'+ pl +'', function() {
       $('#container').load(""+ siteAddress +"load/"+ pl +"/");    
    });
}

$("#button").live("click", myClickHandler);

// And later ...

$(document).unbind('click', myClickHandler);

名称间隔

$("#button").live("click.myNamespace", function(){
    var pl = $(this).attr('rel');
    $.getScript('' + siteAddress + 'min/?js=fjs'+ pl +'', function() {
       $('#container').load(""+ siteAddress +"load/"+ pl +"/");    
    });
});

// And later...

$(document).unbind('click.myNamespace');

更新:

正如@RTPMatt在下面提到的,die()实际上更合适.上述方法可以使用,但是die()易于使用.但是,对于die(),您必须将选择器与调用live()时使用的选择器完全匹配,否则结果可能无法预测:

As @RTPMatt mentions below, die() is actually more appropriate. The method described above will work, but die() is easier to use. However, with die() you must match the selector exactly to the one used when you called live() or the results may be unpredictable:

$("#button").live("click", function(){
    var pl = $(this).attr('rel');
    $.getScript('' + siteAddress + 'min/?js=fjs'+ pl +'', function() {
       $('#container').load(""+ siteAddress +"load/"+ pl +"/");    
    });
});

// And later ...

$('#button').die('click');