简体   繁体   English

防止在页面加载时自动单击按钮

[英]prevent button from being clicked automatically on page load

When the page is loaded, the button is clicked automatically, but I don't want the function display() to be called until I click the button.加载页面时,会自动单击按钮,但我不希望在单击按钮之前调用 function display() 。 How should I fix it?我应该如何解决它?

<button id="button">Click</button>

window.onload = function () {
var button = document.getElementById("button");
button.onclick = display();
}

I tried button.addEventListener("click", display());我试过button.addEventListener("click", display()); but the same problem still occurred.但同样的问题仍然发生。

When using () the function will be called, so use raw display使用()时将调用 function,因此使用原始display

window.onload = function () { var button = document.getElementById("button"); button.onclick = display; }

When you type display() , what you're saying to Javascript is, "I'd like to call the display function now, please."当你输入display()时,你对 Javascript 说的是,“我想现在调用显示 function,拜托。” So when you type所以当你输入

button.addEventListener("click", display());

you're similarly saying to Javascript, "I'd like to attach an event listener to the click event with the result of the display function , please."您对 Javascript 也有类似的说法,“我想将一个事件侦听器附加到 click 事件,并显示 function 的结果。” You want to be saying to Javascript, "I'd like you to attach this function display to the click event, please. Only call it when the button is clicked."您想对 Javascript 说,“我希望您将此 function display附加到单击事件中。请仅在单击按钮时调用它。” How do we do this in Javascript?我们如何在 Javascript 中做到这一点? Pass the function, but don't call it!通过function,但不要调用它!

button.addEventListener("click", display);

Try preventing the defaults尝试阻止默认值

 button.addEventListener("click",(e)=>{ e.preventDefaults(); })

You can have a further study on how the method works on the following link: https://www.w3schools.com/jsref/event_preventdefault.asp您可以通过以下链接进一步研究该方法的工作原理: https://www.w3schools.com/jsref/event_preventdefault.asp

Try this code试试这个代码

 document.getElementById("").addEventListener("click",function(){ functionName; });

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

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