Jquery – 使用.load和selector加载页面不执行脚本?

我正在尝试使用.load()方法将一个页面加载到另一个页面。 这个加载的页面包含一个我想在加载完成后执行的脚本。 我已经整理了一个准系统示例来演示:

index.html的:

  Jquery Test   $(document).ready(function() { $('#nav a').click(function() { $('#contentHolder').load('https://stackoverflow.com/questions/1429927/jquery-loading-a-page-with-load-and-selector-doesnt-execute-script/content.html #toLoad', '', function() {}); return false; }); });     
Content loaded will go here

Content.html:

 
This content is from https://stackoverflow.com/questions/1429927/jquery-loading-a-page-with-load-and-selector-doesnt-execute-script/content.html
This should fade away.
$('#contentDiv').fadeOut('slow', function() {} );

单击链接时,内容应加载,第二段应逐渐消失。 但它不会执行。 如果我在https://stackoverflow.com/questions/1429927/jquery-loading-a-page-with-load-and-selector-doesnt-execute-script/content.html的脚本中粘贴一个简单的警报(“”),它也不会执行。

但是,如果我在.load()调用中取消#toLoad选择器,它可以正常工作。 我不知道为什么会这样,因为块明显在#toLoad div的范围内。 我不想避免使用选择器,因为实际上https://stackoverflow.com/questions/1429927/jquery-loading-a-page-with-load-and-selector-doesnt-execute-script/content.html将是一个完整的HTML页面,我只想要一个选择部分。

有任何想法吗? 如果https://stackoverflow.com/questions/1429927/jquery-loading-a-page-with-load-and-selector-doesnt-execute-script/content.html中的脚本在.load()回调中,它可以正常工作,但我显然不希望index.html中包含该逻辑。

我可能有回调使用.getScript()来加载“https://stackoverflow.com/questions/1429927/jquery-loading-a-page-with-load-and-selector-doesnt-execute-script/content.html.js”然后在那里有逻辑,这似乎工作? 如果可能的话,我宁愿将脚本保留在https://stackoverflow.com/questions/1429927/jquery-loading-a-page-with-load-and-selector-doesnt-execute-script/content.html中,以便在正常加载时它也能正常执行。 事实上,无论如何,我可能会这样做,但我想知道上述原因无效。

如果查看jquery源代码,您将看到.load()方法只是从加载的内容中删除所有脚本(如果指定了选择器)。

  jQuery.ajax({ url: url, type: type, dataType: "html", data: params, complete: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("
") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } }

从外部加载的内容执行的脚本可能存在一些限制。 一些Ajax函数会执行它,有些可能不会。 出于某些不合理的原因,我希望使用带有内容选择器的.load()执行脚本。 这可能是一些无证件但有意的行为。

请记住,您始终可以使用带有.getScript()的回调函数来调用.getScript()

为什么调用JS是加载回调? 那会更清洁

尝试在文档就绪时执行该function

  

可能是因为JS正在尝试执行该function,同时仍然生成DOM。 IMO,这种方法开始并不是很好。 这就像访问私有函数中的公共变量一样。

为什么要在单独的文件中载入? 我只是将inLoad及其子项放在index.html中并在样式表中设置display:none,然后将jQuery show()和hide()函数附加到onclick处理程序以使事物显示或消失。