jquery as follows, and dynamically added tr can also trigger this event
$( "-sharpdataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});
how do I implement this function in native js?
jquery as follows, and dynamically added tr can also trigger this event
$( "-sharpdataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});
how do I implement this function in native js?
function eventDelegate (e,targetSelector,fn) {
//
let event = e || window.event;
//
let target = event.target || event.srcElement;
//
let currentTarget = event.currentTarget;
// matches
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function(s) {
let matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
//
while (target !== currentTarget) {
//
if (target.matches(targetSelector)) {
let sTarget = target;
// this
fn.call(sTarget, Array.prototype.slice.call(arguments))
}
target = target.parentNode;
}
the above boss's method is very marked and forbidden, but it is not suitable for Xiaobai to understand:
first of all, we need to understand what delegate means: the delegate does not bind events to child elements. When clicking on child elements, according to the principle of event bubbling, the event bound on body is triggered. This method can get the event object of the clicked child element, which is relatively simple. The difficulty of
is actually another problem. The dom structure of the child element is usually more than 1 layer, so how to make the event object the one we want? generally, we want the outermost element of the child element. The following chestnut can tell you how to get the event object of the parent node you want:
var a=document.getElementById('content_left');//
a.onclick = function(ev){//ev
var ev = ev || window.event;
var target = ev.target || ev.srcElement;
while(target!=a){//dom
console.log(target.className)
if(target.className == 'c-abstract'){//c-abstract
target.style.background = "-sharpeee";
break;
}
target=target.parentNode;//while,
}
};