简体   繁体   中英

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.

HTML:

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

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. You can just declare it as a function in your base javascript and it should be all good.

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:

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.

put it out of addEventListener

or another way - do onclick attachment inside addEventListener , not in html, like:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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