首页 > 解决方案 > 将JS拆分成多个源文件

问题描述

提前道歉,我有一个关于 JS 的非常愚蠢/基本的问题。

我正在尝试将脚本(在单独的 JS 文件中定义)链接到按钮:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
<script type="text/javascript" src="myscripts.js"></script> 
  </head>
  <body>
     
<input type="button" id="button" value="Button">

<script>
  button.onclick = function() {
    alert('Clicked!');
  };
</script>
     
  </body>
</html

myscripts.js有这个:

function x (){
alert("external fn clicked");
console.log("running x");
}

当我尝试将函数调用替换为index.html停止button.onclick = x();工作时。

我究竟做错了什么?

标签: javascript

解决方案


您需要将 onclick 设置为一个函数,但似乎您正在做的是将其设置为 x 函数的返回值,即undefined.

只需更改button.onclick = x()button.onclick = x.

同样在现代,通常最好使用button.addEventListener(x).

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
  <script>
    function x() {
      alert("external fn clicked");
      console.log("running x");
    }
  </script>
</head>

<body>

  <input type="button" id="button" value="Button">

  <script>
    button.onclick = x;
  </script>

</body>
</html


推荐阅读