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

我一直很沮丧,试图找到通过jQuery加载和卸载一些JS文件的最佳方法,这是我能做的最后一件事:

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

我想要做的是通过jQuery加载一些页面,同时它将包含适当的外部JS文件,用于当前已加载的页面,它第一次正常工作,但是当我再次单击该按钮时,最后一个JS仍然加载,因此它会在同一页面内两次触发JS文件内的函数。

我一直尝试使用.append,也可以通过更改属性并创建dynamicaly 元素但仍然,我得到的结果是相同的。

你不能“卸载”JavaScript。 一旦加载,它就被加载了。 没有撤消。

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

live()unbind()的特例。 实时事件处理程序附加到document而不是元素,因此您必须删除处理程序,如下所示:

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

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

命名处理函数

 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()时使用的选择器完全匹配,否则结果可能无法预测:

 $("#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'); 

你甚至可以拥有一个“占位符函数”并在再次加载脚本之前检查它是否存在。 但是,首先,我认为加载页面并且仅在加载外部脚本之后(并且仅在需要时)才会更好

 $("#button").live("click", function() { var pl = $(this).attr('rel'); //now we load the page, and then the "complete" callback function runs $('#container').load(""+ siteAddress +"load/"+ pl +"/", function() { we check if the function is present into memory if (typeof window["page_" + pl + "_init"] == 'undefined') { //function not found, we have to load the script $.getScript('' + siteAddress + 'min/?js=fjs'+ pl +''); } }); }); 

在外部脚本中,您将需要具有该function

 function page_abcde_init() { //this is just a place holder, or could be the function used //to initialize the loaded script (sort of a document.ready) } 

其中“page_abcde_init()”的“abcde”是被点击元素的值var pl = $(this).attr('rel');