@
oxyflour @
tudou527 @
aivier 完整代码
function $(selector) {
var str = selector.split(' '),
temp,
element = document;
for (var i = 0; i < str.length; i++) {//ID
if (str[i].indexOf('#') === 0) {
temp = str[i].replace('#', '');
element = element.getElementById(temp);
}
else if (str[i].indexOf('.') === 0) {//Class
temp = str[i].replace('.', '');
element = element.getElementsByClassName(temp)[0];
}
else if (str[i].indexOf('#') === -1 && str[i].indexOf('.') === -1 && str[i].indexOf('[') === -1) {//Tag
element = element.getElementsByTagName(str[i])[0];
}
else if (str[i].indexOf('[') === 0 && str[i].indexOf('=') === -1) {//属性
temp = str[i].replace('[', '').replace(']', '');
for (var element = element.getElementsByTagName('*'), j = 0; j < element.length; j++) {
if (element[j].hasAttribute(temp) === true) {
element = element[j];
}
}
}
else {//属性值
temp = str[i].replace('[', '').replace(']', '');
temp = temp.split('=');
element = element.getElementsByTagName('*');
var l = element.length;
for (var j = 0; j < l; j++) {
if (element[j].attributes[temp[0]] != undefined && element[j].attributes[temp[0]].value === temp[1]) {
element = element[j];
}
}
}
}
return element;
}