[英]DOM Manipulation(Click Event Not Working)
I've build an express app and its working perfectly, in the final stage I want to add some alert messages to pop when some button are clicked.我已经构建了一个快速应用程序并且它运行良好,在最后阶段我想添加一些警报消息以在单击某些按钮时弹出。 But my alerts are poping without even clicking, the moment page containing the button is loaded pop up shows但是我的警报甚至没有点击就弹出,加载包含按钮的页面弹出显示
In my index.js
file I have a form button for deleting在我的index.js
文件中,我有一个用于删除的表单按钮
<form
action="/grades/<%=grade._id%>?_method=DELETE"
method="POST"
class="delete-form"
>
<input
type="submit"
class="btn btn-danger mt-3"
value="Delete Class"
id="delBtn"
>
</form>
I've given ID delBtn
for the button, and inside my main.js
I have我已经为按钮提供了 ID delBtn
,在我的main.js
我有
var delBtn = document.querySelector('#delBtn');
delBtn.addEventListener('click', alert('Button Clicked'));
How can I get this to work properly..我怎样才能让它正常工作..
This line is the problem.这条线是问题所在。 You call alert
immediatelly.你立即alert
。
delBtn.addEventListener('click', alert('Button Clicked'));
it will behave just like this它会像这样
alert('Button Clicked');
delBtn.addEventListener('click', undefined);
The addEventListener
function expects a string and a function but you are not passing in a function but undefined
since that is what alert
function returns. addEventListener
function 需要一个字符串和一个 function 但您没有传入 function 但undefined
,因为这是alert
function 返回的内容。
So all you need is this所以你只需要这个
delBtn.addEventListener('click', function(){
alert('Button Clicked');
});
I think you missed callback function in event listener我想你错过了事件监听器中的回调 function
delBtn.addEventListener('click', function(){alert('Button Clicked')});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.