Skip to content
New issue

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

DOM事件的捕获、冒泡和委派 #33

Open
Liqiuyue9597 opened this issue Aug 15, 2020 · 0 comments
Open

DOM事件的捕获、冒泡和委派 #33

Liqiuyue9597 opened this issue Aug 15, 2020 · 0 comments

Comments

@Liqiuyue9597
Copy link
Owner

Liqiuyue9597 commented Aug 15, 2020

首先讲事件的捕获和冒泡

代码题:
有上万个<li>标签,实现点击显示<li>标签里的内容

  <ul class="show">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>

解题思路:用事件委派实现,不要傻傻地想着给每个<li>绑定事件。
事件委托:将事件统一绑定给元素的共同祖先元素。当后代元素上的事件触发时,会一直冒泡到祖先元素,进而实现只绑定一次事件可应用到多个元素上。

var ulList = document.getElementsByClassName('show')[0]

ulList.addEventListener('click', function(e){
  if(e.target.tagName === 'LI'){
    console.log(e.target.innerHTML)
  }
})

写的时候面试官顺带问e.targete.currentTarget区别
e.target是指的触发当前事件的标签
e.currentTarget指的是绑定事件的标签(所以不会变)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant