JavaScript事件监听器与事件处理器 [英] JavaScript Event Listeners vs Event Handlers
问题描述
addLoadEvent(converter);
//转换器
函数转换器(){
var pixels = document.getElementById(pixels);
pixels.addEventListener(keyup,updateNode,true);
pixels.addEventListener(keydown,updateNode,true);
}
但这并不是,只能运行一次。
addLoadEvent(converter);
//转换器
函数转换器(){
var pixels = document.getElementById(pixels);
pixels.onkeydown = updateNode;
pixels.onkeyup = updateNode;
}
我缺乏什么...有什么区别?任何指向该主题的链接都会有所帮助。
我的假设是,处理程序应该像侦听程序一样行事,但事实并非如此。实际上,侦听器甚至需要添加到addLoadEvent函数中?
设置 onxxxxx
设置 那个函数的事件处理程序。
从 Mozilla开发者中心 :
addEventListener寄存器单个目标上的单个事件侦听器。事件目标可能是文档中的单个节点,文档本身,窗口或XMLHttpRequest。
要为目标注册多个事件侦听器,请致电
请参阅 同一文档的这一章 ,以便比较旧的 onxxxx
方式。
Ok, I have been trying to figure this out for a long time now and finally have the time to investigate. As the title suggests "What is the difference"? I know that this works the way I want it to.
addLoadEvent(converter);
// Converter
function converter() {
var pixels = document.getElementById("pixels");
pixels.addEventListener("keyup", updateNode, true);
pixels.addEventListener("keydown", updateNode, true);
}
But this doesn't, and only runs once.
addLoadEvent(converter);
// Converter
function converter() {
var pixels = document.getElementById("pixels");
pixels.onkeydown = updateNode;
pixels.onkeyup = updateNode;
}
What I'm I lacking... What is the difference? Any links to the topic would be helpful.
My assumption was that the handler should act like the listener but it doesn't. In fact does a listener even need to be added to the addLoadEvent function?
addEventListener
adds an event handler function to the event. There can be an unlimited number of event handlers this way.
Setting onxxxxx
sets the event handler to that one function.
From the Mozilla Developer central:
addEventListener registers a single event listener on a single target. The event target may be a single node in a document, the document itself, a window, or an XMLHttpRequest.
To register more than one event listeners for the target, call addEventListener for the same target but with different event types or capture parameters.
And see this chapter of the same document for a comparison of the old onxxxx
way.
这篇关于JavaScript事件监听器与事件处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!