Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...