我有两组包含<script>
函数的JavaScript标记块,并将它们按优先级排序。其中一个标记包含一个src
到另一个外部.js库文件,如下所示。
<script src='libtest.js'>
function helloworld() {
alert('hello world');
}
function callLibraryTest() {
runLibraryTest(); //Calls into libtest.js for auto test.
}
</script>
... some html ...
<script>
function callHello() {
helloworld();
}
</script>
我得到的错误是callHello()
函数没有定义helloworld()
。我该怎么解决呢?
请注意,脚本是故意分开的,因为如果它们被捆绑在一起,调用callHello()
也可能没有定义。
谢谢。
发布于 2015-08-28 04:03:32
如果<script>
标记具有src
属性,则它也不能包含脚本文本。将helloworld
函数移动到单独的<script>
标记。
<script src="libtest.js"></script>
<script>
function helloworld() {
alert('hello world');
}
function callLibraryTest() {
runLibraryTest(); // Calls into libtest.js for auto test.
}
</script>
<!-- some html ... -->
<script>
function callHello() {
helloworld();
}
</script>
发布于 2015-08-28 05:36:36
假设您在成功加载"callHello“函数时试图运行"libtest.js”函数。正如Dan已经解释的那样,带有src属性的标记不能在其正文中包含javascript代码。您可以尝试类似回调方法的技巧。例如,将src标记修改为"libtest.js?callback=callHello“,并在libtest.js的末尾执行回调方法。
希望这能有所帮助!
https://stackoverflow.com/questions/32263138
复制相似问题