Event delegation is actually realized by using event bubbling mechanism.
Principle: add the event to the parent element, and judge whether the event source (target element) is the element tag you want to trigger. If it is triggered, it is not triggered.
Event bubbling: after the child element event is triggered, the event with the same name of the parent element will be called in turn until window, and the event bubbling will exist by default.
// / / find ul // var ul = document.getElementsByTagName('ul')[0]; // //Add new li // document.getElementById('btn1').onclick = function(){ // var li = document.createElement('li'); // li.innerHTML = "I'm the new li"; // ul.appendChild(li); // } // var list = document.getElementsByTagName('li'); // for(var i = 0; i < list.length; i++){ // list[i].onclick = function(){ // alert('clicked '); // } // } // If I want the li created later to have a click event, it will be added to ul (because all li's are clicked, the event will bubble, and all the events will bubble to ul) // But I just want to add click events to li. Now you can add click events directly to ul, which means that all elements in ul have click events. // How to ensure that I only let li have click events? // ul.onclick = function(e){ // e = e || window.event; // //console.log(e.target); / / get the event source (target element) // //I just need to judge whether the event source is li. Only li can execute the code. // //console.log(e.target.nodeName); //nodeName node name. If it is a label, it will get the label name (in uppercase). // if(e.target.nodeName == 'LI'){ // alert('clicked '); // } // } // $('li').click(function(){ // alert('clicked '); // }) // Add events to ul and delegate events // Event delegation: the newly added elements can also have events $('ul').on('click','li',function(){ alert('Be ordered.'); }) // $('#btn1').click(function(){ // //Create a new li to add to ul // $('< li > I am the new Li < / Li >'). Appendto ($('ul ')); // });
Event bubbling: it exists by default, which means that the event with the same name of the parent element will be called in turn after the event of the child element is triggered
trigger('event name ')
Calling an event with code
$('.box').click(function () { alert('div Be ordered.'); }); // Now I want to click the button. Besides the event that triggers the button, I also want to trigger the click event of div. $('#btn1').click(function () { alert('The button is on'); // trigger // Click event of code calling box (simulating that someone clicked div) $('.box').trigger('click'); });