简体   繁体   中英

How to associate Javascript functions with buttons?

javascript

html

I feel as though I am doing this correctly, but for whatever reason, it isn't working. I've made sure that the link to my Javascript file is present and in correct syntax.

 <script src="speedreader.js" type="text/javascript"></script>

in the header.

I have

<button id="start" onclick="start();" type="button">Start</button>

This is obstrusive Javascript, but it won't work with

    var startButton = document.getElementByID("start");
    startButton.onclick = start;

so I've had no choice but to resort to it.

My function that I'm attempting to associate with this button is the most basic thing. Just to test to see if a Javascript function will work at all.

function start() {
        alert("this is working");
    }

If you're loading your script in the header and are trying to getElementById there, the element won't yet be parsed/created .

Put the <script> tag which loads your script at the end of the page, or at least listen for the DOM to be ready before you try to bind elements.

Try this

 function myFunction() { alert("HELLO WORLD"); } 
 <button onclick="myFunction()">Click me</button> 

Turned on your javascipt in browser 在此处输入图片说明

When you're trying to assign event handler for onclick in code you should write:

var startButton = document.getElementById("start");
if (startButton)
  startButton.click = start;

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