我正在开发一个 JavaScript 库,并使用此函数来匹配元素:
$ = function (a)
{
var x;
if (typeof a !== "string" || typeof a === "undefined"){ return a;}
//Pick the quickest method for each kind of selector
if(a.match(/^#([\w\-]+$)/))
{
return document.getElementById(a.split('#')[1]);
}
else if(a.match(/^([\w\-]+)$/))
{
x = document.getElementsByTagName(a);
}
else
{
x = document.querySelectorAll(a);
}
//Return the single object if applicable
return (x.length === 1) ? x[0] : x;
};
有时我希望过滤这个函数的结果,比如挑选出一个 div span
,或者一个 #id div
或其他相对简单的选择器。
我该如何过滤这些结果?我可以创建一个文档片段,并在该片段上使用 querySelectorAll 方法吗?还是必须采用手动字符串操作的方法?
我只关心现代浏览器和 IE8+。
如果您想查看我的整个库,可以点击此处:https://github.com/timw4mail/kis-js
编辑:
澄清一下,我想要能够做类似 $_(selector).children(other_selector) 这样的事情,并返回与该选择器匹配的子元素。
编辑:
所以这是我对最简单的选择器的潜在解决方案:
tag_reg = /^([\w\-]+)$/;
id_reg = /#([\w\-]+$)/;
class_reg = /\.([\w\-]+)$/;
function _sel_filter(filter, curr_sel)
{
var i,
len = curr_sel.length,
matches = [];
if(typeof filter !== "string")
{
return filter;
}
//Filter by tag
if(filter.match(tag_reg))
{
for(i=0;i<len;i++)
{
if(curr_sell[i].tagName.toLowerCase() == filter.toLowerCase())
{
matches.push(curr_sel[i]);
}
}
}
else if(filter.match(class_reg))
{
for(i=0;i<len;i++)
{
if(curr_sel[i].classList.contains(filter))
{
matches.push(curr_sel[i]);
}
}
}
else if(filter.match(id_reg))
{
return document.getElementById(filter);
}
else
{
console.log(filter+" is not a valid filter");
}
return (matches.length === 1) ? matches[0] : matches;
}
它接受像 div
、id 或类选择器这样的标签,并使用 curr_sel
参数返回匹配的元素。
我不想使用完整的选择器引擎,有更好的方法吗?