JavaScript 函数无法在外部文件中运行

标签 javascript dom

我在外部文件中有两个函数,然后我在HEAD脚本中调用A和B,A可以运行而B不能,但是如果我将B放入head脚本中,B也可以运行。我不知道为什么,我能做什么?

HTML:

<head>
<script language="JavaScript" type="text/JavaScript">
<!--
function B(id) {
    var selected = document.getElementById(id)
    var arr = selected.options[selected.selectedIndex].text.split(" ");
    var value = ""
    for (var i = 1; i < arr.length; i++) {
        if (value != "") value = value + " ";
        value = value + arr[i];
    }
    return value;
}

function save() {
    A("msg");
    var x = B(id);
}
-->
...
<script type="text/JavaScript" src="js/my.js"></script>
</body>
...

我的.js:

function A(msg) {
    scroll(0,0);
    var outerPane = document.getElementById('FreezePane');
    var innerPane = document.getElementById('InnerFreezePane');
    if (outerPane) outerPane.className = 'FreezePaneOn';
    if (innerPane) innerPane.innerHTML = msg;
}

function B(id) {
    var selected = document.getElementById(id)
    var arr = selected.options[selected.selectedIndex].text.split(" ");
    var value = ""
    for (var i = 1; i < arr.length; i++) {
        if (value != "") value = value + " ";
        value = value + arr[i];
    }
    return value;
}

最佳答案

最安全的做法是将代码包装在 window.onload 的头部中。像这样的处理程序...

<head>
  <script type="text/javascript">
    window.onload = function(){
      // your external files are guaranteed to be loaded now
      // you can call A or B
    }
  </script>
</head>

onload 仅在加载所有外部脚本后才会触发。

这是一个完整的示例...

index.html

<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script>
function save() {
  A()
  B()
}

window.onload = function() {
  save()
}
</script>
</head>

<body>
The content of the document......
<script src="./external.js"></script>
</body>

</html>

external.js

function A() {
  alert('A ran')
}

function B() {
  alert('B ran')
}

注意:这比将外部脚本移动到头部更好,就像其他答案所建议的那样,因为在头部加载的外部资源会阻止整个页面渲染,直到它们被加载为止。

通过将外部脚本留在 body 标记的末尾,页面加载会显得更快,因为 css/html 将立即显示。即使 JavaScript 尚未加载。

关于JavaScript 函数无法在外部文件中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44448172/

相关文章:

javascript - AngularJS 确认密码验证

javascript - jQuery 中最近的祖先节点

Javascript/jQuery : Set Values (Selection) in a multiple Select

javascript - 正则表达式:用于限制字母数字字符的总长度,包括所有组

javascript - Typescript Cannot write file 会覆盖输入文件。编译 Ionic 3 应用程序时出错

javascript - 与 Bootstrap 按钮关联的 jQuery 函数仅执行一次

javascript - 相对表单操作解析为绝对 URL?

javascript - 是否有可能检测到 DOM 中的变化并使其不发生?

两个标签之间文本的 Javascript If 语句

javascript - 外部 javascript 文件中的 PHP 导致它无法加载