JavaScript:什么是addEventListener? [英] JavaScript: What is addEventListener?

查看:142
本文介绍了JavaScript:什么是addEventListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个功能是什么?没有找到任何好的例子。

What is this function? Didn't really find any good examples.

推荐答案

addEventListener 方法是 W3C标准方法将事件处理程序附加到元素,以便在触发事件时可以执行一些有用的操作。以下示例将在单击id my_image_id 的元素时弹出警告消息:

The addEventListener method is the W3C standard method to attach an event handler to an element, so that you can do something useful when an event is triggered. The following example would popup an alert message when the element with id my_image_id is clicked:

function doSomething() {
   alert('Image clicked');
}

var myImage = document.getElementById('my_image_id');

myImage.addEventListener('click', doSomething, false);

不幸的是,这在Internet Explorer中不起作用,因为Microsoft使用不同的事件注册模型。在Internet Explorer 5+中,您必须按如下方式附加事件处理程序:

Unfortunately this does not work in Internet Explorer, since Microsoft uses a different event registration model. In Internet Explorer 5+, you would have to attach the event handler as follows:

myImage.attachEvent('onclick', doSomething);

因此,对于跨浏览器事件注册方法,您可以使用反射并有条件地执行:

Therefore for a cross browser event registration method, you can use reflection and execute conditionally:

function addEventHandler(node, type, f) {
   if (node.addEventListener) {
      node.addEventListener(type, f, false);
   } 
   else if (node.attachEvent) {
      node.attachEvent("on" + type, f);
   } 
   else {
      node["on" + type] = f;
   }
}

var myImage = document.getElementById('my_image_id');

addEventHandler(myImage, 'click', doSomething);

进一步阅读:

  • Mozilla Dev Center: element.addEventListener
  • Quirksmode: Advanced event registration models
  • Douglas Crockford: The Theory of the DOM

这篇关于JavaScript:什么是addEventListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆