简体   繁体   English

我无法弄清楚为什么我添加事件处理程序的简单尝试无效

[英]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.

相关问题 无法弄清楚为什么我的change(...)事件处理程序在这种情况下不起作用 - Can't figure out why my change(…) event handler isn't working in this scenario 我的简单路由无法正常工作,我不知道为什么 - My simple routing is not working and I can't figure out why 经典的元音练习。 我不知道为什么我的for循环无法正常工作 - classic vowel exercise. I can't figure out why my for loop isn't working 我不知道为什么我的石头,剪刀布游戏中的得分不起作用 - I can't figure out why the scoring isn't working in my rock, paper, scissors game wp_add_inline_script没有向我的页面添加任何内容,无法弄清原因 - wp_add_inline_script isn't adding anything to my page, can't figure out why 我不知道为什么我的JavaScript无法正常工作…我正在将值动态传递给标签 - I can't figure out why my javascript isn't working… I'm dynamically passing values to a tag 无法弄清楚为什么JS插件无法正常工作 - Can't figure out why JS plugin isn't working 似乎无法弄清楚该脚本为何不起作用 - Can't seem to figure out why the script isn't working 无法弄清楚为什么它不起作用了 - Can't figure out why it isn't working, anymore 似乎无法弄清楚为什么我的JavaScript无法在IE和Chrome中运行 - Can't seem to figure out why my javascript isn't working in IE and Chrome
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM