js之 matches (可以取代jq的 delegate 方法)

时间:2020-12-12 22:41:31

问题:请给#wrap 下面的子元素添加点击事件!

<div id="wrap">
<a class="btn" href="http://www.lyblog.net">点击代码</a>
<span class="btn">不可点击按钮</span>
</div>

jq的写法

//jQueryObject.on( events [, selector ] [, data ], handler )
$('#wrap').on('click', 'a.btn', function (e) {
console.log(1111);
})

js 写法

 document.querySelector('#wrap').addEventListener("click", function (e) {
if (e.target.matches('a.btn')) {
console.log(111);
}
});

由于 'matches'支持情况也不太尽人意

通常在开发阶段兼容IE 8+及移动端,我更偏向于脱离jq等重量级的库。所以有了以下的兼容写法:

function matchesSelector(element, selector){
if(element.matches){
return element.matches(selector);
} else if(element.matchesSelector){
return element.matchesSelector(selector);
} else if(element.webkitMatchesSelector){
return element.webkitMatchesSelector(selector);
} else if(element.msMatchesSelector){
return element.msMatchesSelector(selector);
} else if(element.mozMatchesSelector){
return element.mozMatchesSelector(selector);
} else if(element.oMatchesSelector){
return element.oMatchesSelector(selector);
}
}

但主要IE 8正好不支持msMatchesSelector方法,可以用如下方法处理以上函数,以便支持IE 8,完善之后的代码如下:

function matchesSelector(element,selector){
if(element.matches){
return element.matches(selector);
} else if(element.matchesSelector){
return element.matchesSelector(selector);
} else if(element.webkitMatchesSelector){
return element.webkitMatchesSelector(selector);
} else if(element.msMatchesSelector){
return element.msMatchesSelector(selector);
} else if(element.mozMatchesSelector){
return element.mozMatchesSelector(selector);
} else if(element.oMatchesSelector){
return element.oMatchesSelector(selector);
} else if(element.querySelectorAll){
var matches = (element.document || element.ownerDocument).querySelectorAll(selector),
i = 0; while(matches[i] && matches[i] !== element) i++;
return matches[i] ? true: false;
}
throw new Error('Your browser version is too old,please upgrade your browser');
}

第二部分  替换jquery的 closest

  Closest 获得匹配选择器的第一个祖先元素,从当前元素开始沿 DOM 树向上。

    //jquery
$("selector").closest();
//js
function closest(el,selector){
const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
while (el){
if(matchesSelector.call(el,selector)){
return el;
}else {
el = el.parentElement;
}
}
return null;
}

本文参考:http://www.lyblog.net/detail/601.html

     https://github.com/oneuijs/You-Dont-Need-jQuery/blob/master/README.zh-CN.md