日期:2014-05-16  浏览次数:20319 次

js选择元素

String.prototype.startWith = function () {
return this.charAt(0);
};
String.prototype.content = function () {
return this.substring(1, this.length);
};
function getTagName(str) {
if (typeof str == "string") {
return document.getElementsByTagName(str);
}
}
function $(x) {
var reg = /^[A-Za-z]+$/;
if (typeof x == "string") {
if (x.startWith() == "#") {
return document.getElementById(x.content());
} else {
if (x.startWith() == ".") {
var l = getTagName("*").length;
var e = getTagName("*");
var elements = [];
for (var i = 0; i < l; i++) {
if (e[i].className == x.content()) {
elements.push(e[i]);
}
}
if (l == -1) {
return elements[0];
} else {
return elements;
}
} else {
if (reg.test(x.startWith())) {
if (reg.test(x)) {
var l = getTagName(x).length;
var e = getTagName(x);
var eObj = [];
for (var i = 0; i < l; i++) {
eObj.push(e[i]);
}
return eObj.join(",");
} else {
var key = x.substring(0, x.indexOf("["));
var attr = x.substring(x.indexOf("@") + 1, x.indexOf("="));
var name = x.substring(x.indexOf("=") + 1, x.indexOf("]"));
var value = [];
var l = getTagName(key).length;
var e = getTagName(key);
for (var i = 0; i < l; i++) {
if (e[i][attr] == name) {
if (e[i].checked == true) {
value.push(e[i].value);
}
}
}
return value.join(",");
}
}
}
}
} else {
return x;
}
}