gpt4 book ai didi

javascript - live addEventListener 鼠标输入

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:35:04 25 4
gpt4 key购买 nike

我有 jQuery 的代码:

$(document).on("mouseenter","a",function(e){
//...
});

如何使用原生 JavaScript(不使用 jQuery)创建相同的内容?

我只需要 Chrome 兼容。

最佳答案

对于相同的功能,您可以将多个事件监听器添加到单个元素,请使用以下内容:

addEventListener('mouseover', function(e) {
if (e.target instanceof HTMLAnchorElement) {
//...
}
});

这将完全相同。对于其他选择器:

addEventListener('mouseover', function(e) {
if (e.target instanceof HTMLAnchorElement) {
//matches if the element is an <a>
}
if (e.target.className.match(/(\s|^)foobar(\s|$)/)) {
//matches if the element has the class "foobar" in its classes list
}
if (e.target.id == 'baz') {
//matches if the element has an id of "baz"
//same syntax works for attributes like 'name', 'href', 'title', etc.
}
if (e.target instanceof HTMLLabelElement && e.target.attributes.for.value == 'baz') {
//matches a <label> tag that has its 'for' attribute set to 'baz'
//the element.attributes.attrName.value is the syntax for getting the value
// of any attribute that isn't available otherwise
}
});

委托(delegate) mouseenter 事件的问题在于,它仅在应用它的元素悬停时触发。换句话说,如果您将 mouseenter 事件附加到文档,就像在您的 jQuery 代码中一样,它只会在用鼠标输入 document 时触发,但不会为任何子级触发。要让它对 child 起作用,您需要使用 mouseover

关于javascript - live addEventListener 鼠标输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21352145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com