如何从函数中删除 jquery 过滤器
how to remove jquery filter from function
我有一个函数要从 jQuery 中删除:
var hunt = new RegExp(action.search);
$('a').filter(function() {
return hunt.test(this.href);
}).click(doStuff);
我正在尝试使用 vanilla javascript 重写此函数。这是我目前所拥有的,但它不起作用
var hunt = new RegExp(action.search);
var aSelector = document.getElementsByTagName('a');
var arr = Array.prototype.filter.call(aSelector, function(el){
return hunt.test(el.href)
});
for(var i=0; i<arr.length; i++){
var elem = arr[i].getAttribute('href');
elem.onclick = function(){
doStuff();
};
}
我猜测 jQuery 选择器的行为与 document.getElementsByTagName 略有不同,但我真的不知道发生了什么。任何帮助将不胜感激。谢谢
最好使用 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);
}
});
我有一个函数要从 jQuery 中删除:
var hunt = new RegExp(action.search);
$('a').filter(function() {
return hunt.test(this.href);
}).click(doStuff);
我正在尝试使用 vanilla javascript 重写此函数。这是我目前所拥有的,但它不起作用
var hunt = new RegExp(action.search);
var aSelector = document.getElementsByTagName('a');
var arr = Array.prototype.filter.call(aSelector, function(el){
return hunt.test(el.href)
});
for(var i=0; i<arr.length; i++){
var elem = arr[i].getAttribute('href');
elem.onclick = function(){
doStuff();
};
}
我猜测 jQuery 选择器的行为与 document.getElementsByTagName 略有不同,但我真的不知道发生了什么。任何帮助将不胜感激。谢谢
最好使用 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);
}
});