简体   繁体   中英

How to add an event handler in Javascript?

I have a listener on DOMContentLoaded which calls startup() function.

I want to add more listeners (within the startup function) to items added to the DOM in the startup function. But it seems to fail (no click event registetered)

I use item.addEventListener("click", f, false); where f is the function that is supposed to run.

NOTE: I CANNOT use onclick=... I also cannot use JQuery.

Demo code is here

You have several issues in your code:

  1. previous function is not defined
  2. To attach a click event via addEventListener, the event name is click not onclick .
  3. You are calling addListeners outside of your load function.

Here is a jsfiddle that works: http://jsfiddle.net/VUgRu/

You should always use the javascript console to see what errors you are getting.

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...

 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;
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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