2011-04-01 57 views
0

我有一个问题。如何使用jquery.load()加载脚本?

在我的文件content.html中我有脚本。 当使用jQuery的load()函数加载此页面时,页面会显示,但脚本不起作用。我认为这是因为选择者。

我该如何解决这个问题?

编辑:

$(document).ready(function(){ 
$('#content').load('content.html #toLoad', function(){}); 
}) 

感谢

+2

你需要对这个问题不是很清楚 – amosrivera 2011-04-01 23:09:09

+0

工作,不要空的第二个参数传递给'.load()'。那应该完成什么? content.html中的页面是否包含ID为'toLoad'的元素? – 2011-04-01 23:10:10

回答

5

当你说“剧本不行”你的意思是存在的JavaScript在你通过AJAX加载页面?

它不会工作,至少不会直接。

你有两种选择。从已加载的内容中解析出脚本,然后使用eval来运行它。

更好的方法是使用$.getScript加载(并执行)javascript。如果您想将您的JavaScript与您已加载的HTML绑定,那么您需要一些约定来识别脚本。例如,你可以有一个标签在你的动态加载HTML:

<span style="display:none;" id="script">/scripts/somescript.js</span>

然后寻找与ID =“脚本”当您加载内容的跨度,如果你找到它,使用$.getScript加载脚本它确定。

例如...

$.load('content.html #toLoad', function(data){ 
    var $script = $(data).find('span[id=script]'); 
    if ($script.length) { 
     $.getScript($script.html()); 
     // remove the span tag -- no need to render it 
     $script.remove(); 
    } 
    $('#content').html(data); 
}); 
+0

如何使用$ .getScript与id =“script”? – Steffi 2011-04-01 23:19:04

+0

请参阅编辑,您必须从标签中提取数据。 – 2011-04-01 23:23:08

+0

你为什么要做'.getScript($ script.html());'?如果我的脚本内联(content.html'内),我必须做些什么?不是外部文件'blabla.js' – Steffi 2011-04-01 23:33:07