使用纯 Javascript 将事件绑定到元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17820401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bind event to element using pure Javascript
提问by Wancieho
I'm writing an API and unfortunately need to avoid any jQuery or 3rd party libraries. How exactly are the events bound to elements through jQuery?
我正在编写一个 API,不幸的是需要避免使用任何 jQuery 或 3rd 方库。事件是如何通过 jQuery 绑定到元素的?
jQuery example:
jQuery 示例:
$('#anchor').click(function(){
console.log('anchor');
});
I'm close to writing a onClick attribute on the element out of frustration, but I would like to understand the link between the jQuery event and DOM element.
出于沮丧,我即将在元素上编写 onClick 属性,但我想了解 jQuery 事件和 DOM 元素之间的链接。
How exactly does the element know to fire a jQuery event when the markup itself is not changed? How are they catching the DOM event and overriding it?
当标记本身没有改变时,元素究竟如何知道触发 jQuery 事件?他们如何捕捉 DOM 事件并覆盖它?
I have created my own Observer handler but cant quite understand how to link the element to the Observer events.
我已经创建了自己的观察者处理程序,但不太明白如何将元素链接到观察者事件。
回答by Dan Tao
Here's a quick answer:
这是一个快速的答案:
document.getElementById('anchor').addEventListener('click', function() {
console.log('anchor');
});
Every modern browser supports an entire API for interacting with the DOM through JavaScript without having to modify your HTML. See here for a pretty good bird's eye view: http://overapi.com/javascript
每个现代浏览器都支持一个完整的 API,用于通过 JavaScript 与 DOM 交互,而无需修改您的 HTML。在这里看到一个很好的鸟瞰图:http: //overapi.com/javascript
回答by txpeaceofficer09
You identify the element by id, in this case anchor, by:
您可以通过 id(在本例中为锚点)通过以下方式识别元素:
var el = document.getElementById('anchor');
Then you need to assign your click event:
然后你需要分配你的点击事件:
el[window.addEventListener ? 'addEventListener' : 'attachEvent']( window.addEventListener ? 'click' : 'onclick', myClickFunc, false);
And finally, the event's function would be something like:
最后,事件的功能将类似于:
function myClickFunc()
{
console.log('anchor');
}
You could simplify it or turn it into a one-liner if you do not need compatibility with older browsers and and a range of browsers, but jQuery does cross-browser compatibility and does its best to give you the functionality you are looking for in as many older browsers as it can.
如果您不需要与旧浏览器和一系列浏览器的兼容性,您可以将其简化或将其变成单线,但 jQuery 具有跨浏览器兼容性,并尽最大努力为您提供您正在寻找的功能尽可能多的旧浏览器。