Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

dom events - Emulate jQuery "on" with selector in pure Javascript

I would emulate in pure Javascript the main functionality of jQuery .on( events , selector , data) method.

For example

$(document).on('click','.button',function() {
   console.log("jquery onclick"); 
});

I thought it was enough make something like this

document.addEventListener('click',function(e) {
    if(e.target.className == 'button2') {
         console.log("It works");   
    }
});

However when I have this html structure:

<button class="button2">Hello <span>World</span></button>

my script doesn't works when the click event is triggered on span element, because e.target is span. (I ignore for this question the complexity of elements with multiple class, and crossbrowsers compatibility)

The source of jQuery is not simple to read and I don't understand how it works (because the first piece of code, in jQuery, works with my html structure).

I need this method because my html is dynamic, and buttons with this class are created, deleted and re-created many times. I don't want add listeners every times.

I would avoid, if possible, to include jquery library.

So, I can do this?

Here the jsFiddle for testing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update for 2017: current DOM standards like closest mean this is now much easier.

const addEventForChild = function(parent, eventName, childSelector, cb){      
  parent.addEventListener(eventName, function(event){
    const clickedElement = event.target,
    matchingChild = clickedElement.closest(childSelector)
    if (matchingChild) cb(matchingChild)
  })
};

To use it just:

addEventForChild(parent, 'click', '.child', function(childElement){
  console.log('Woo click!', childElement)
})

Here's a jsfiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...