We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
No description provided.
The text was updated successfully, but these errors were encountered:
在解析事件委托之前,我们先回顾一下js中的事件流,即冒泡和捕获。
① .冒泡:当下级节点触发某个事件的时候,该事件会逐级向上触发上级节点的同类事件。
② .捕获:和冒泡类似,只不过事件的顺序相反。即是从上级节点传递到下级节点
事件委托就是基于js的事件流产生的,事件委托是利用事件冒泡,将事件加在父元素或者祖先元素上,触发该事件。
<body> <div id="myDiv"> <input type="button" value="按钮1" id="btn1"> <input type="button" value="按钮2" id="btn2"> <input type="button" value="按钮3" id="btn3"> </div> </body> <script type="text/javascript"> document.getElementById("myDiv").onclick=function(e){ e=window.event||e; var btnId=e.target.id; switch(btnId){ case "btn1": console.log("按钮1"); break; case "btn2": console.log("按钮2"); break; case "btn3": console.log("按钮3"); break; } } </script>
上面的代码就是一个典型的事件委托案例。利用的原理就是事件冒泡,将事件加载父元素上,通过event参数来区别按钮的不同
通过对上面事件委托代码的观察,我们可以很容易得出事件委托的好处:
① .减少页面绑定事件数量,由于页面事件绑定数量越多,页面执行性能越差,所以事件委托可以提高页面的性能
② .事件委托可以灵活的处理子节点动态变化的场景,无论子节点增加还是减少,事件都无需重新绑定
使用场景:比如给UL下的子元素li绑定事件。
Sorry, something went wrong.
No branches or pull requests
No description provided.
The text was updated successfully, but these errors were encountered: