Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/430.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按钮单击页面重新加载上的事件激发_Javascript_Events_Dom Events - Fatal编程技术网

Javascript 按钮单击页面重新加载上的事件激发

Javascript 按钮单击页面重新加载上的事件激发,javascript,events,dom-events,Javascript,Events,Dom Events,我在向按钮元素添加事件时遇到问题 问题: <form id="contact_form"> (Some form fields here) <button id="form_submit" value="send">Send</button> </form> <script src="contact_form.js"></script> var submit_button = document.getEle

我在向按钮元素添加事件时遇到问题

问题

<form id="contact_form">
    (Some form fields here)
    <button id="form_submit" value="send">Send</button>
</form>
<script src="contact_form.js"></script>
var submit_button = document.getElementById('form_submit');

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

function test_click_event()
{
     alert("Button clicked");
}
该函数应该是事件处理程序,在页面重新加载和单击按钮时激发

我希望它只有在点击按钮时才会启动

这是我的代码:

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>
var submit_button = document.getElementById('form_submit');

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

function test_click_event()
{
     alert("Button clicked");
}
我正在使用Chrome进行调试。

()方括号调用函数执行删除它们或使用以下命令:

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

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

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


不需要括号

您可以保留括号,但需要添加匿名函数。 请看这里:

例如:

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

为什么不直接用onClick来代替呢?@pattyd你的意思是onClick事件而不是单击,或者在HTML中添加
?是的,这就是我的意思。。。那就容易多了,我还是不知道你的意思。再次阅读我的评论,我问“某物或某物”:(如果你的意思是在html标记中添加事件-我只想让js与html完全分离。它们被称为括号;)