简体   繁体   English

即使未单击按钮,也会触发按钮上的 onClick 事件

[英]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?问题是,由于某种原因,在页面加载时无需单击按钮, logInToPod()函数就会被调用,而我编写的代码应该只添加事件侦听器,而不是在单击按钮之前调用该函数,对吗?

I'm using webpack, I don't know if that matters or is causing this.我正在使用 webpack,我不知道这是否重要或是否导致了这种情况。

I see 2 major issues:我看到两个主要问题:

  1. onClick should be onclick ; onClick应该是onclick
  2. logInToPod() should be logInToPod . logInToPod()应该是logInToPod

So I would suggest to modify your code like:所以我建议修改你的代码,如:

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

Here a JSFiddle example.是一个 JSFiddle 示例。

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.出现这个问题是因为您使用括号直接调用 logInToPod 函数,这意味着它将在执行window.load的同一时间进行评估。 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.这里的logIntoPod是一个指向函数的指针,它将在点击事件被触发时进行评估。

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

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