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

手写事件代理(委托) #72

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

手写事件代理(委托) #72

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@JeromeD3
Copy link

JeromeD3 commented Apr 9, 2023

function addEventListener(element, type, fn, selector) {
if (!selector) {
element.addEventListener(type, fn)
} else {
element.addEventListener(type, function (event) {
const target = event.target
if (target.matches(selector)) {
fn.call(target, event)
}
})
}
}

@kangkang123269
Copy link

function addEventListener(element, type, fn, selector) {
    // 检查元素、类型和回调函数是否存在
    if (!element || !type || !fn) {
        return;
    }

    // 如果没有选择器,则直接添加事件监听器
    if (!selector) {
        element.addEventListener(type, fn);
        return;
    }

    // 添加带有事件代理的监听器
    element.addEventListener(type, function (event) {
        let targets = Array.from(element.querySelectorAll(selector));
        
        if (targets.includes(event.target)) {
            fn.call(event.target, event);
        }
   });
}

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

No branches or pull requests

3 participants