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

查看:133
本文介绍了使用纯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事件?我们创建了我自己的Observer处理程序,但是不了解如何将元素链接到Observer事件。

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?

>

推荐答案

这是一个快速的答案:

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

每个现代浏览器都支持整个API,通过JavaScript与DOM进行交互,而无需修改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天全站免登陆