使用纯Javascript将事件绑定到元素 [英] Bind event to element using pure Javascript

查看:120
本文介绍了使用纯Javascript将事件绑定到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个API,不幸的是需要避免任何jQuery或第三方库。如何通过jQuery将事件绑定到元素?

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?

jQuery示例:

$('#anchor').click(function(){
    console.log('anchor');
});

我接近写一个onClick属性的元素出于挫折,但我想了解jQuery事件和DOM元素之间的链接。

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.

当标记本身没有改变时,元素如何知道触发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?

我创建了我自己的Observer处理程序,但是不知道如何将元素链接到Observer事件。

I have created my own Observer handler but cant quite understand how to link the element to the Observer events.

推荐答案

以下是一个简单的答案:

Here's a quick answer:

document.getElementById('anchor').addEventListener('click', function() {
  console.log('anchor');
});

每个现代浏览器都支持通过JavaScript与DOM交互的整个API,而无需修改HTML。在这里查看相当不错的俯瞰图: http://overapi.com/javascript

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

这篇关于使用纯Javascript将事件绑定到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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