After New Year’s Day, the first article of the New Year.
Original Intention: Many interviews will involve event commissioning. I have read many blog posts one after another. They are all very good and each has its own merits. I have to think about it myself, for my own review in the future, and at the same time To provide front-end partners who are looking for a job with a seemingly more comprehensive place to interpret event delegation to understand its principles, this article summarizes two versions of event delegation: javascript, jquery;
Use event bubbling, onlyspecify an event handler to manage all events of a certain type.
The number of event handlers added to the page in js directly affects the running performance of the web page. Because each event processing function is an object, the object will occupy memory, and the more objects in the memory, the result will be worse performance; and the more times the DOM is accessed, it will cause the structure to be redrawn or redrawn. The number of rows will also increase, which will delay the interactive readiness time of the entire page;
For new DOM elements added after the page is processed, event delegation can be used to provide new DOM elements for the new DOM elements. Elements are added and subtracted together with event handlers;
<p> </p><p>第一个p</p> <p>第二个p</p> <p>第三个p</p> <p> </p><p>这是子集菜单</p> <p>我是子集的p </p><p>我是子集的p</p> <button>点击加一</button>
If event delegation is not used in js: get all the p tags in the page and then use a for loop to traverse and add event processing functions to each element
let nodes = document.getElementById("nodes"); let ps = document.getElementsByTagName("p"); console.log(ps); let btn = document.getElementsByTagName("button")[0]; let inner = 33; btn.onclick = function() { inner++; let p = document.createElement("p"); p.innerHTML = inner + "新增的p标签啊"; nodes.appendChild(p); console.log(ps); }; for (let i= 0;i<ps.length><p>At this time, after running it in the browser, I tested it and found the result as shown in Figure 1; </p><p><img src="https://img.php.cn/upload/image/376/157/896/1593567746839219.png" title="1593567746839219.png" alt="javascript event delegation and jquery event delegation"></p><p>So how can js be given to new users without event delegation? What about adding event handlers for added tags? The solution is as follows: </p><pre class="brush:php;toolbar:false">let nodes = document.getElementById("nodes"); let ps = document.getElementsByTagName("p"); console.log(ps); let btn = document.getElementsByTagName("button")[0]; let inner = 33; btn.onclick = function () { inner++; let p = document.createElement("p"); p.innerHTML = inner + "新增的p标签啊"; nodes.appendChild(p); addEvent();//将新dom元素增加到页面后再执行循环函数 console.log(ps); }; function addEvent() { for (let i = 0; i <p>At this time, the browser runs as shown in Figure 2:</p><p><img src="https://img.php.cn/upload/image/129/624/157/1593567770605067.png" title="1593567770605067.png" alt="javascript event delegation and jquery event delegation"></p><p>At this time, although adding events for new dom elements is solved There is a problem with the processing function, but after careful consideration, its performance has declined compared to before. The reason is that another event processing function (object) has been added, which once again takes up memory; therefore, events will be used at this time Delegation, the advantages of event delegation are also reflected at this time: </p><pre class="brush:php;toolbar:false">let nodes = document.getElementById("nodes"); let ps = document.getElementsByTagName("p"); console.log(ps); let btn = document.getElementsByTagName("button")[0]; let inner = 33; btn.onclick = function () { inner++; let p = document.createElement("p"); p.innerHTML = inner + "新增的p标签啊"; nodes.appendChild(p); console.log(ps); }; //事件委托,为nodes指定一个事件处理函数,处理nodes下为p标签的所有元素的cilck事件 nodes.onclick= function(e){ let ev = e || window.event let target = ev.target || ev.srcElement //srcElement IE浏览器 //这里要判被处理元素节点的名字,也可以增加相应的判断条件 target.nodeName.toLowerCase() == 'p'||target.nodeName.toLowerCase() == 'span',但是要注意不要使用父级元素的名称,因为再点击子元素之间的空气的时候,由于事件冒泡他会给父级元素也增加相应的事件处理函数;因为返回的节点名称一般都是大写,所以这时要用toLowerCase()处理一下; if(target.nodeName.toLowerCase() == 'p'){ target.style.background = 'green' } }
At this time, the result of running in the browser is shown in Figure 3:
Compared with js event delegation, the advantages of jquery event delegation: When executing event delegation, only the child element will trigger the event function, and the parent element executed on its behalf will not. The event function will be triggered, so there is no need to judge the name of the element node; (Note that the event delegation method here is on, if the bind method is used, the parent element will trigger the event function)
All nodes under the node here The child nodes labeled p are all assigned event processing functions; the child nodes here can also be multiple similar to 'p, span'. It should be noted that the same labels as nodes cannot be written here, otherwise the intervals between click elements The event processing function will be assigned to p under nodes; for example, Example 2:
Example 1:
let inner = 33; //这里nodes节点下所有标签为p的子节点都被赋予事件处理函数;这里的子节点还可以是多个类似' p,span',需要注意这里面也不可以写同nodes一样的标签,否则点击元素之间的间隔会给nodes下的p赋予事件处理函数 $('#nodes').on('click','p',function(e){ let target = $(e.target) target.css('backgroundColor','red') }) $('button').click(()=>{ inner++; $('#nodes').append($('<p>我是新增加的p标签'+inner+'</p>')) })
The effect of browser operation is shown in Figure 4:
##Example 2:
<p> </p><p>第一个p</p> <p>第二个p</p> <p>第三个p</p> <span>span</span> <p> </p><p>这是子集菜单</p> <p>我是子集的p </p><p>我是子集的p</p> <button>点击加一</button> <script> let inner =33; $('#nodes').on('click','p,p,span',function(e){ let target = $(e.target) target.css('backgroundColor','red') }) $('button').click(()=>{ inner++; $('#nodes').append($('<p>我是新增加的p标签'+inner+'')) }) </script>
<p> <input> <input> </p> <p> </p> <script></script> <script> let events = document.getElementById('events'); let content = document.getElementById('content'); events.onclick=function(e){ let ev = e || window.event; let target = ev.target || ev.srcElement; if(target.nodeName.toLowerCase()=='input'){ switch(target.id){ case 'addHandle': return addEvent(); break case 'deleteHandle': return deleteEvent(); break } } } function addEvent(){ let add = document.createElement('p') add.innerHTML = '这是增加按钮' content.appendChild(add) } function deleteEvent(){ let del = document.createElement('p') del.innerHTML = '这是删除按钮' content.appendChild(del) } </script>
$('#events').on('click','input',(e)=>{ let target = $(e.target); switch(target[0].id){ case 'addHandle': return addEvent(); break case 'deleteHandle': return deleteEvent(); break } }) function addEvent(){ $('#content').append($('<p>这是增加按钮</p>')) } function deleteEvent(){ $('#content').append($('<p>这是删除按钮</p>')) }
JS Tutorial"
The above is the detailed content of javascript event delegation and jquery event delegation. For more information, please follow other related articles on the PHP Chinese website!