【问题标题】:jQuery feature with pure JS [duplicate]纯 JS 的 jQuery 功能 [重复]
【发布时间】:2022-02-21 18:06:12
【问题描述】:

选择器上有功能点击绑定

$(document).on("click", ".onClass", function () {
    //your code
    var element = $(this); // to get clicked element
});

有没有纯js的类比?

附:我已经看到了这个解决方案How to get the element clicked (for the whole document)?,但这不是我所期待的解决方案。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以以相同的方式将事件侦听器绑定到文档,但您需要测试目标元素以查看它或其祖先之一是否与选择器匹配。

    document.addEventListener('click', (event) => {
        const selector = ".onClass";
        const element = event.target;
        if (!element.closest(selector)) return; // No match so abort here
        // Otherwise: Do stuff with element
    });
    
    猜你喜欢
    • 2019-02-21
    • 2013-01-29
    • 2015-02-02
    • 2022-12-08
    • 2023-04-06
    • 2014-04-19
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多