javascript - How to implement jquery's on() method in native js.
我想大声告诉你
我想大声告诉你 2017-07-05 10:56:31
0
2
1135

How does native js implement jquery's on() method and support binding multiple events to an element at the same time?

For example:

element.on('click mouseout',function(){...});

How to achieve this using native JS?

我想大声告诉你
我想大声告诉你

reply all(2)
ringa_lee

Give you a simple example. If you want to use the on method in native JS, you can write it like this:

HTMLElement.prototype.on = function(events, callback){
    let evs = events.split(' ');
    for(let event of evs){
        this.addEventListener(event, callback);
    }
    // 如果你想像JQuery一样支持链式调用,可以在这里返回this
    // return this;
}

There are many loopholes in this way of writing, because many situations are not considered. For example, IE's event binding is not considered. For example, multiple events do not consider multiple callbacks.

But. After all, the purpose is to tell you your thoughts, not to reinvent the wheel for you.

The implementation of JQuery probably follows the same logic. You can use this method to encapsulate your own library.

typecho

addEventListener

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!