hol*_*321 4 javascript jquery google-chrome addeventlistener
我有jQuery的代码:
$(document).on("mouseenter","a",function(e){
//...
});
Run Code Online (Sandbox Code Playgroud)
如何使用本地JavaScript(不使用jQuery)创建相同的代码?
我只需要兼容Chrome。
对于相同的功能,可以将多个事件侦听器添加到单个元素,请使用以下命令:
addEventListener('mouseover', function(e) {
if (e.target instanceof HTMLAnchorElement) {
//...
}
});
Run Code Online (Sandbox Code Playgroud)
这将完全相同。对于其他选择器:
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
}
});
Run Code Online (Sandbox Code Playgroud)
委派mouseenter事件的问题在于,仅当将其应用于其上的元素悬停时才触发。换句话说,如果将mouseenter事件附加到文档,就像在jQuery代码中一样,则仅在document使用鼠标输入时才会触发,但不会对任何子级触发。为了使它适用于儿童,您需要使用mouseover。