如何在javascript中调用一个在html文件中声明的函数

How to invoke a function in javascript which has been declared in a html file

本文关键字:html 一个 文件 声明 函数 javascript 调用      更新时间:2023-09-26

我有一个html文件,其中函数displayJsonWithAjax和函数displayOtherJsonWithAjax在脚本标记中声明。

在另一个脚本标记中,当选择框更改时,我用以下代码调用这些函数:

<script>
import fetchJson from 'some.module'
function displayJsonWithAjax() {
     ...
}
function displayOtherJsonWithAjax() {
     ...
}
</script>
<script>
$(document).ready(function () {
    $('#selectBox').change(function () {
        displayJsonWithAjax();
        displayOtherJsonWithAjax();
    }).change();
});
</script>

当用浏览器调试时,我得到以下错误:

ReferenceError: displayJsonWithAjax is not defined

如果我尝试将所有的函数放在同一个script标签中,当浏览器加载页面时不会自动执行任何代码…如何调用这两个函数?

import fetchJson from 'some.module'

那真的有用吗?检查控制台

如果脚本行失败,该行之后的所有内容都不会执行,因此脚本函数不会被声明,也不会在其他地方可用(这也解释了为什么"如果我尝试将所有函数放在同一个script标签中,浏览器加载页面时不会自动执行代码":脚本在第1行失败,并且不会执行任何其他内容)。

test();
<script>function test(){
alert('hello');
}</script>