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

事件的target/currentTarget的区别 #71

Open
Liqiuyue9597 opened this issue Sep 28, 2020 · 1 comment
Open

事件的target/currentTarget的区别 #71

Liqiuyue9597 opened this issue Sep 28, 2020 · 1 comment

Comments

@Liqiuyue9597
Copy link
Owner

Liqiuyue9597 commented Sep 28, 2020

target表示你当前点击的那个标签,currentTarget表示你绑定事件的那个标签。
这个之所以经常考是因为英文是反的,currentTarget意思明明是当前目标的意思但是实际代码不是这样的。
如果遇到事件委托,把事件绑定到父元素,点击子元素的时候,target就是子元素,currentTarget是父元素。

@Liqiuyue9597
Copy link
Owner Author

Liqiuyue9597 commented Sep 28, 2020

这个一般会出一道题考察。
pdd:给无数个

  • 标签绑定点击,当点击相应的标签
  • 时输出里面的文字内容。
    这道题点击事件肯定要绑定要父元素
      的,给子标签一个一个绑定事件是很费资源的。

      var ul = document.querySelector('ul');
      ul.onclick = function(e){
        console.log(e.target.innerText); //这里应该写e.target
      }

      bytedance:编写一个事件委托通用工具on。一个专门做事件委托的函数。
      比如:

      //将button事件委托给`div1`
      on("click", "#div1", "button", () => {
        console.log("button被点击了");
      });
      function on(eventType, element, selector, fn) {
        // 如果element不是一个元素,就获取element所在的元素
        if (!(element instanceof Element)) {
          element = document.querySelector(element);
        }
        element.addEventListener(eventType, e => {
          const t = e.target;
          // matches判断一个元素是否满足一个选择器
          if (t.matches(selector)) {
            fn(e);
          }
        });
      }
  • 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