简体   繁体   English

按钮单击事件在页面重新加载时触发

[英]Button click event fires on page reload

I have problem with adding event to button element.我在向按钮元素添加事件时遇到问题。

Problem :问题

Function supposed to be event handler fires on page reload and when I click button.函数应该是事件处理程序在页面重新加载和单击按钮时触发。

I want it to fire only when button is clicked.我希望它仅在单击按钮时触发。

This is my code:这是我的代码:

index.html file : index.html 文件

<form id="contact_form">
    (Some form fields here)
    <button id="form_submit" value="send">Send</button>
</form>
<script src="contact_form.js"></script>

contact_form.js file : contact_form.js 文件

var submit_button = document.getElementById('form_submit');

submit_button.addEventListener("click", test_click_event());

function test_click_event()
{
     alert("Button clicked");
}

I'm using Chrome to debug.我正在使用 Chrome 进行调试。

submit_button.addEventListener("click", test_click_event);

不需要括号

() brackets call to function execute remove them or use this: () 括号调用函数执行删除它们或使用这个:

var submit_button = document.getElementById('form_submit');

    submit_button.addEventListener("click", function(){test_click_event();});

    function test_click_event()
    {
         alert("Button clicked");
    }

Demo演示

You can keep the brackets but you need to add an anonymous function.您可以保留括号,但需要添加匿名函数。 See here: https://www.w3schools.com/jsref/met_document_addeventlistener.asp请参阅此处: https : //www.w3schools.com/jsref/met_document_addeventlistener.asp

For example:例如:

submit_button.addEventListener("click", function (){
    test_click_event();
});

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

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