简体   繁体   English

如何在Javascript中添加事件处理程序?

[英]How to add an event handler in Javascript?

I have a listener on DOMContentLoaded which calls startup() function. 我在DOMContentLoaded上有一个侦听器,该侦听器调用startup()函数。

I want to add more listeners (within the startup function) to items added to the DOM in the startup function. 我想将更多侦听器(在启动功能内)添加到在启动功能中添加到DOM的项目中。 But it seems to fail (no click event registetered) 但是它似乎失败了(没有注册点击事件)

I use item.addEventListener("click", f, false); 我使用item.addEventListener("click", f, false); where f is the function that is supposed to run. 其中f是应该运行的函数。

NOTE: I CANNOT use onclick=... I also cannot use JQuery. 注意:我不能使用onclick = ...我也不能使用JQuery。

Demo code is here 演示代码在这里

You have several issues in your code: 您的代码中有几个问题:

  1. previous function is not defined 未定义previous功能
  2. To attach a click event via addEventListener, the event name is click not onclick . 要通过addEventListener附加click事件,事件名称为click not onclick
  3. You are calling addListeners outside of your load function. 您正在load函数之外调用addListeners

Here is a jsfiddle that works: http://jsfiddle.net/VUgRu/ 这是一个有效的jsfiddle: http : //jsfiddle.net/VUgRu/

You should always use the javascript console to see what errors you are getting. 您应该始终使用JavaScript控制台来查看正在遇到的错误。

Using no frameworks (no excuse to use them) and adding an event listener in standard compliant browsers and Internet Explorer 8 and older for attachEvent... 不使用框架(不使用任何借口),并在符合标准的浏览器和Internet Explorer 8及更早版本的AttachEvent中添加事件监听器...

 if (window.addEventListener) {document.addEventListener('keydown',keyPressed,false);}
 else {document.attachEvent('onkeydown',keyPressed);}

function keyPressed(evt)
{
 var e = evt || event;
 var key = e.which || e.keyCode;

 switch (key)
 {
  case 77:// M
  alert('m key pressed');
  break;

  case 76://L
  alert('L key pressed');
  break;
 }
}

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

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