从一个js文件中分离出来的,还不知道作者是谁。
在指定的DOM节点context下按CSS2,CSS3选择器的定义去找出相关的DOM节点
支持的选择器:
E[att^="val"],E[att$="val"],E[att*="val"],E[att~="val"],E[att|="val"],E[att!="val"],E[att="val"]
E:enabled,E:disabled,E:checked,E:not(s)
+ E.class
> E.class
E.class
E#id
E
参数:pattern:CSS2 Selector可以通过逗号分隔多个选择器,context指定要查找的DOM节点范围
返回值:[DOM Collection]
function selector(pattern, context) {
var re = new RegExp('([a-z]*)([\.#:]*)(.*|$)', 'ig');
var match = re.exec(pattern);
//alert(context);
var conditions = [];
if (match[2] == '#') conditions.push(['id', match[3]]);
else if(match[2] == '.') conditions.push(['className', match[3]]);
else if(match[2] == ':') conditions.push(['type', match[3]]);
var s = match[3].replace(/\[(.*)\]/g,'$1').split(<a href="mailto:'@'">'@'</a>);
for(var i=0; i<s.length; i++) {
var cc = null;
if (cc = /([\w]+)([=^%!$~]+)(.*)$/.exec(s[i])){
conditions.push([cc[1], cc[2], cc[3]]);
}
}
var list = (context || document).getElementsByTagName(match[1] || "*");
if(conditions) {
var elements = [];
var attrMapping = {'for': 'htmlFor', 'class': 'className'};
for(var i=0; i<list.length; i++) {
var pass = true;
for(var j=0; j<conditions.length; j++) {
var attr = attrMapping[conditions[j][0]] || conditions[j][0];
var val = list[i][attr] || (list[i].getAttribute ? list[i].getAttribute(attr) : '');
var pattern = null;
if(conditions[j][1] == '=') {
pattern = new RegExp('^'+conditions[j][2]+'$', 'i');
} else if(conditions[j][1] == '^=') {
pattern = new RegExp('^' + conditions[j][2], 'i');
} else if(conditions[j][1] == '$=') {
pattern = new RegExp(conditions[j][2] + '$', 'i');
} else if(conditions[j][1] == '%=') {
pattern = new RegExp(conditions[j][2], 'i');
} else if(conditions[j][1] == '~=') {
pattern = new RegExp('(^|[ ])' + conditions[j][2] + '([ ]|$)', 'i');
}
if(pattern && !pattern.test(val)) {
pass = false;
break;
}
}
if(pass) elements.push(list[i]);
}
return elements;
} else {
return list;
}
}
如果你读了我的文章,觉得有帮助:
说明
发表评论



您测试过没 很大的BUG 没改过代码暂时取不到对象的
[回复]