2012-01-18 101 views
0

我使用jQuery的加载函数来加载链接的内容,当它被点击时,除了页面内的JavaScript之外,所有工作都很好。jQuery的加载函数,其他JS不起作用?

我猜这是因为它只是没有得到应用到新的内容。
我看了一下$.getScript函数,但我没有完全理解它,而我尝试过的方法并不起作用。

中的JavaScript我创建至今:

var dest = new Array(4); 
dest[0] = window.location.href; 
dest[1] = 'content/index.php'; 
dest[2] = 'content/slideshow.php'; 
dest[3] = 'content/scaffold.php'; 
dest[4] = 'content/elements.php'; 
dest[7] = 'content/404.php'; 

function loadcontent(d, b, p, newclass) { 
var stateObj = { foo: p }; 
if (b == 'yes') { 
    $('#bgdiv').html('<img id="bg" src="images/bg_bokeh.jpg" style="width:100%;height:100%;" />'); 
} else { 
    $('#bgdiv').html(''); 
} 
document.body.className = newclass; 
if (dest[d] == 'content/slideshow.php') { 
    $.getScript('js/external-slideshow.js'); 
} 

$.getScript('js/scripts.js'); 
$.getScript('js/plugins.js'); 
$.getScript('js/modernizr.js'); 

$('#page-content').load(dest[d]); 

    history.pushState(stateObj, p, p); 
} 

而且我用我的链接代码:上面列出的3个js文件

<a href="javascript:loadcontent('3', 'yes', 'about.php', 'page page-id-269 page-template-default');">about</a> 

我已经为onload功能(脚本,插件,modernizr),他们不会再次执行$.getScript函数吗?或者我必须找到另一种方式来重新加载onload函数?

感谢

编辑
菲尔的回答工作。我只是在错误的地方getScript调用。哎呀!

回答

1

onload包含JS文件中的函数在加载时不会执行,因为onload事件仅在加载页面(以及页面中的HTML中定义的所有内容)时才会发生。根据jQuery docs for $.getScript,您可以将函数作为第二个参数传递给$ .getScript,该函数在文件加载时执行;您可以在其他文件中执行onload中的操作,或者让该函数调用包含文件中的函数。

+0

我有多个$(窗口).load函数,因此我无法调用每个函数。有什么办法让它重新运行JS文件?或者,我是否会更好地创建一个XMLHTTPRequest?那会再次运行JS代码吗? –

+0

你可以做的一件事是在其他JS文件中使用命名函数,并使用$(window).load(namedFunction)[或$(namedFunction)],然后使用该命名函数作为第二个参数$ .getScript [所以你会有$ .getScript(url,namedFunction)]。 – Phil

+0

这会解决很多我的问题,但是我使用jQuery和其他一些JS插件,所以我不认为我可以将它们全部转换为命名函数 –