我有一个函数,我想从中删除jQuery:
formatoptions
我正在尝试使用vanilla javascript重写此函数。到目前为止,这是我所拥有的,但它无法正常工作
var hunt = new RegExp(action.search);
$('a').filter(function() {
return hunt.test(this.href);
}).click(doStuff);
我猜jQuery选择器的行为与document.getElementsByTagName略有不同,但我真的不知道发生了什么。任何帮助将不胜感激。感谢
答案 0 :(得分:2)
更好地使用querySelectorAll()
代替getElementsByTagName()
,除此之外,我认为代码是自我解释的。询问是否有不清楚的事情
//a very basic utility to fetch Nodes by css-selectors and return them as an Array
//- shorthand for document.querySelectorAll()
//- document.querySelectorAll() returns a NodeList wich lacks the Array-methods
//- second argument to provide a Node as the context of the query
function $$(selector, context){
return Array.from((typeof context === "object" && context || document).querySelectorAll(selector));
}
//now we can use the regular Array-methods
$$('a').filter(function(node){
return hunt.test(node.href);
}).forEach(function(node){
node.addEventListener("click", doStuff);
})
或者这样:
$$('a').forEach(function(node){
if(hunt.test(node.href)){
node.addEventListener("click", doStuff);
}
});