简体   繁体   中英

onClick event on a button fires even if the button is not clicked

I'm trying to add an event listener to a button, here is the code I used:

window.onload = function(){
    document.getElementById('loginButton').onClick = logInToPod();
}

The problem is that for some reason the logInToPod() function gets called as soon as the page loads without clicking the button, while the code I wrote should just add the event listener, and not call the function until I click the button, right?

I'm using webpack, I don't know if that matters or is causing this.

I see 2 major issues:

  1. onClick should be onclick ;
  2. logInToPod() should be logInToPod .

So I would suggest to modify your code like:

window.onload = function(){
    document.getElementById('loginButton').onclick = logInToPod;
}

Here a JSFiddle example.

This problem is coming because you are calling logInToPod function directly with parenthesis, which means it will be evaluated at the same thime as the window.load will get executed. You should call it via a pointer, as I had listed below

 window.onload = function(){ document.getElementById('loginButton').onclick = logInToPod; } function logInToPod() { alert("You have clicked me!"); }
 <button id="loginButton">Click me to alert</button>

Here logIntoPod is a pointer that is pointing to the function and it will be evaluated with the click event will be triggered.

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