[英]I can't figure out why my simple attempt at adding an event handler isn't working
I'm trying to add a click event to a button on my web page. 我正在尝试将click事件添加到我的网页上的按钮。 Its a simple button created with a tag and I set the id attribute to "button1".
它是一个用标签创建的简单按钮,我将id属性设置为“button1”。 In the javascript code, I used getElementById to store the button in the variable btn and used the onClick method to add the click event.
在javascript代码中,我使用getElementById将按钮存储在变量btn中,并使用onClick方法添加click事件。 The function is basic and only displays an alert box.Simple, right?
该功能是基本的,只显示一个警告框。简单,对吧?
But for some reason, clicking the button doesn't do anything. 但由于某种原因,单击按钮不会执行任何操作。 I don't see where I went wrong.
我不明白我哪里出错了。 I double checked my spelling everywhere, so it isn't a typo.
我仔细检查了我的拼写,所以这不是一个错字。 Did I miss a step somewhere?
我错过了某个地方吗?
<html>
<head>
<title>Add Event Handler</title>
<head>
<body>
<h1>Add Event Handler</h1>
<button id="button1">Click Me</button>
<script>
function test(){
alert("The event handler was set.");
}
var btn = document.getElementById("button1");
btn.onClick = test;
</script>
</body>
btn.onclick = test;
not 不
btn.onClick = test;
<html> <head> <title>Add Event Handler</title> <head> <body> <h1>Add Event Handler</h1> <button id="button1">Click Me</button> <script> function test(){ alert("The event handler was set."); } var btn = document.getElementById("button1"); btn.onclick = test; </script> </body>
理想情况下,您应该使用EventTarget.addEventListener()
btn.addEventListener('click', test, false)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.