有人能解释一下 jQuery 的 getScript()
的行为吗?功能?
考虑一个 javascript 文件 test.js
:
var tmp = 'a variable';
alert('here');
当 test.js
通过 html 的 <script>
加载标签,一切正常:tmp
变量在全局范围内可用,并出现一个消息框。
我试图通过这段代码获得类似的行为:
<script>
$(document).ready(function() {
$.getScript("static/js/proto/test.js");
setTimeout(function() {
// at this point tmp should be available
// in the global scope
alert(tmp);
} , 2000); // 2 seconds timeout
}
</script>
但是浏览器的错误控制台报告“Undefined variable tmp”错误。 我究竟做错了什么? 谢谢。
最佳答案
$.getScript可以是异步的,使用回调参数:
$.getScript("static/js/proto/test.js", function() {
// here you are sure that the script has been executed
});
请参阅 $.getScript 的文档:http://api.jquery.com/jQuery.getScript
关于javascript - jQuery.getScript() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7269758/