简体   繁体   English

在ajax加载回调函数中调用getScript

[英]calling getScript inside an ajax load callback function

Can somebody please explain this to me. 有人可以向我解释一下。 The goal here is to load via an ajax call an external html, and then load and execute an external script associated with that html code. 这里的目标是通过ajax调用加载外部html,然后加载并执行与该html代码关联的外部脚本。

Code A: 代码A:

$('#content').load(toLoad,function(){
        $.getScript("toLoadScript.js");
});

Code B: 代码B:

$('#content').load(toLoad,showNewContent());
function showNewContent() {
    $.getScript("toLoadScript.js");
}

Code C: 代码C:

$('#content').load(toLoad,showNewContent);
function showNewContent() {
    $.getScript("toLoadScript.js");
}

Why is it that only Code C succesfully loads and executes the script while the other 2 doesn't. 为什么只有代码C成功加载并执行脚本,而其他两个却没有成功。

question related to: Jquery: Run script after ajax load() 有关的问题: jQuery:在ajax load()之后运行脚本

Partial answer: why Code B doesn't work 部分答案: 为什么代码B不起作用

In Code B you are invoking .load as follows: 在代码B中,您按以下方式调用.load

$('#content').load(toLoad,showNewContent());

Which essentially breaks down into: 本质上分为:

var newContent = showNewContent();
$('#content').load(toLoad,newContent);

So you are invoking showNewContent and passing the result of that into .load . 所以你调用showNewContent和传球的处理结果放入.load

This is not what you want to do. 这不是您想要的。 Instead you should pass the function itself (and not its result) to load : 相反,您应该将函数本身(而不是其结果)传递给load

$('#content').load(toLoad,showNewContent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM