简体   繁体   English

单击 html 按钮时,如何使用外部 javascript 文件调用 function?

[英]How to use an external javascript file to call on function when a html button is clicked?

I am trying to create a button that will add text when clicked.我正在尝试创建一个单击时将添加文本的按钮。 It works when the javascript is in the html file but does not when I link it externally.当 javascript 位于 html 文件中时,它可以工作,但当我将其从外部链接时则不起作用。

HTML: HTML:

<input id="ex" type="text">
<button onclick="createList()">Create List</button>
<p id="demo">Click button</p>
<script src="app.js"></script>

Javascript: Javascript:

    document.addEventListener("DOMContentLoaded", () => {
      function createList() {
        var x = document.getElementById("ex").value;
        document.getElementById("demo").innerHTML = x;
      }
    })

By declaring your createList() function inside the event callback, you are actually scoping this function to the callback itself.通过在事件回调中声明您的 createList createList() function,您实际上是将此 function 限定为回调本身。 You can just declare it as a function in your base javascript and it should be all good.您可以在您的基础 javascript 中将其声明为 function,它应该一切都好。

Before:前:

document.addEventListener("DOMContentLoaded", () => {
function createList() {
    var x = document.getElementById("ex").value;
    document.getElementById("demo").innerHTML = x;
}

After:后:

function createList() {
  var x = document.getElementById('ex').value;
  document.getElementById('demo').innerHTML = x;
}

If you want to wait for the DOM to be loaded before you declare your function, then you should attach your listener inside of the event callback like this:如果您想在声明 function 之前等待 DOM 被加载,那么您应该像这样在事件回调中附加您的侦听器:

document.addEventListener("DOMContentLoaded", () => {
  document.getElementById('myButton').onclick = function() {
    var x = document.getElementById('ex').value;
    document.getElementById('demo').innerHTML = x;
  }
});

createList is inside another function (arrow function of addEventListener), so it is not accessible in your html. createList 在另一个 function 中(addEventListener 的箭头 function),因此在 html 中无法访问它。

put it out of addEventListener把它从addEventListener中取出

or another way - do onclick attachment inside addEventListener , not in html, like:或其他方式 - 在addEventListener中执行 onclick 附件,而不是在 html 中,例如:

document.addEventListener("DOMContentLoaded", () => {
  document.getElementById('myButton').onclick = function() {
    var x = document.getElementById("ex").value;
    document.getElementById("demo").innerHTML = x;
  }
});

You can do this你可以这样做

<input id="ex" type="text">
<button onclick="createList()">Create List</button>
<p id="demo">Click button</p>
<script src="app.js"></script>

APP.JS APP.JS

  function createList() {
    var x = document.getElementById("ex").value;
    document.getElementById("demo").innerHTML = x;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM