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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…