Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

事件监听 addEventListener #35

Open
5Mi opened this issue Jun 24, 2016 · 0 comments
Open

事件监听 addEventListener #35

5Mi opened this issue Jun 24, 2016 · 0 comments

Comments

@5Mi
Copy link
Owner

5Mi commented Jun 24, 2016

参考

  • 绑定事件监听
element.addEventListener(<event-name>, <callback>, <use-capture>);

表示在 element 这个对象上面添加一个事件监听器,当监听到有 事件发生的时候,调用 这个回调函数。至于 这个参数,表示该事件监听是在“捕获”阶段中监听(设置为 true)还是在“冒泡”阶段中监听(设置为 false)。关于捕获和冒泡,我们会在下面讲解。

  • 移除事件监听

当我们为某个元素绑定了一个事件,每次触发这个事件的时候,都会执行事件绑定的回调函数。如果我们想解除绑定,需要使用 removeEventListener 方法:

element.removeEventListener(<event-name>, <callback>, <use-capture>);

需要注意的是,绑定事件时的回调函数不能是匿名函数,必须是一个声明的函数,因为解除事件绑定时需要传递这个回调函数的引用,才可以断开绑定。例如:

var fun = function() {
    // function logic
};


element.addEventListener('click', fun, false);
element.removeEventListener('click', fun, false);

一个非常棒的关于事件捕获与事件冒泡的demoClick on a layer to watch the event move through the DOM tree.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant