One of the questions that will be asked during the interview is to let the handwritten DOM delegate the event
In general, write the following:
Ul. AddEventListener (' click ', function (e) {if (e. arget. TagName. ToLowerCase () = = = 'li') {the console. The log (' click the li ')}})Copy the code
And I’m actually going to write it like this
on:function(element,eventType,selector,fn){ element.addEventListener(eventType,e=>{ let el = e.target while(! el.matches(selector)){ if(element === el){ el = null break; } el = el.parentNode } el && fn.call(el,e,el) }) return element }Copy the code