-
Notifications
You must be signed in to change notification settings - Fork 5
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
Labels
Comments
这个一般会出一道题考察。 这道题点击事件肯定要绑定要父元素
var ul = document.querySelector('ul');
ul.onclick = function(e){
console.log(e.target.innerText); //这里应该写e.target
} bytedance:编写一个事件委托通用工具 //将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
target表示你当前点击的那个标签,currentTarget表示你绑定事件的那个标签。
这个之所以经常考是因为英文是反的,currentTarget意思明明是当前目标的意思但是实际代码不是这样的。
如果遇到事件委托,把事件绑定到父元素,点击子元素的时候,target就是子元素,currentTarget是父元素。
The text was updated successfully, but these errors were encountered: