addClass removeClass switchClass getElementsByClass
Array 的删除方法 remove removeAt has
1. 关于 class 的相关操作
// element 对象是否有className
function hasClass(element, className) {
if (element == null)
return false;
var reg = new RegExp(‘(\\s|^)’ + className + ‘(\\s|$)’);
return element.className.match(reg);
}
// 为element 对象添加className
function addClass(element, className) {
if (!hasClass(element, className)) {
element.className += ” ” + className;
}
}
// 删除element 对象的className
function removeClass(element, className) {
if (hasClass(element, className)) {
var reg = new RegExp(‘(\\s|^)’ + className + ‘(\\s|$)’);
element.className = element.className.replace(reg, ‘ ‘);
}
}
// 切换element对象的className 有则删除 没有就添加
function switchClass(element, className) {
if (hasClass(element, className)) {
var reg = new RegExp(‘(\\s|^)’ + className + ‘(\\s|$)’);
element.className = element.className.replace(reg, ‘ ‘);
} else {
element.className += ” ” + className;
}
}
// 获得某个对象下面 所有的含有class 的子对象
function getElementByClassName(className, tag, parent) {
parent = (typeof parent == “string”) ? $(parent) : parent;
if (!parent) {
return false;
}
var tags = (tag == ‘*’ && parent.all) ? parent.all : parent
.getElementsByTagName(tag);
var elements = new Array();
className = className.replace(/\-/g, ‘\\-’);
var regex = new RegExp(‘(^|\\s)’ + className + ‘(\\s|$)’);
var element;
for ( var i = 0, l = tags.length; i < l; i++) {
element = tags[i];
if (regex.test(element.className)) {
elements.push(element);
}
}
return elements;
}
2. 关于Array对象的删除方法
function array_has(val) {
var flag = false;
for ( var i = 0; i < this.length; i++) {
if (this[i] == val) {
flag = true;
}
}
return flag;
}
Array.prototype.has = array_has;
function array_remove(val) {
for ( var i = 0; i < this.length; i++) {
if (this[i] == val) {
for ( var j = i; j < this.length – 1; j++) {
this[j] = this[j + 1];
}
this.length = this.length – 1;
}
}
}
Array.prototype.remove = array_remove;
function array_removeAt(index) {
if (index < this.length) {
for ( var i = index; i < this.length – 1; i++) {
this[i] = this[i + 1];
}
this.length = this.length – 1;
}
}
Array.prototype.removeAt = array_removeAt;