剛剛看了下jQuery的源代碼,其中關于CSS及className的操作思想確實很不錯,值得借鑒。
其中關于jQuery.className.has的定義部分,是用的正則來實現的,其實此處直接利用Javascript中String對象的indexOf方法來作處理的話,比用正則效率會更些,因此 代碼如下:
jQuery.className.has的定義可以改進成:
has: function( t, c ) {
t = t.className || t;
t = " " + t + " ";
c = " " + c + " ";
return t.indexOf(c)>-1;
}
原代碼中關于CSS及className的操作部分節選如下:
代碼如下:
className: {
// internal only, use addClass("class")
add: function( elem, c ){
jQuery.each( c.split(//s+/), function(i, cur){
if ( !jQuery.className.has( elem.className, cur ) )
elem.className += ( elem.className ? " " : "" ) + cur;
});
},
// internal only, use removeClass("class")
remove: function( elem, c ){
elem.className = c ?
jQuery.grep( elem.className.split(//s+/), function(cur){
return !jQuery.className.has( c, cur );
}).join(" ") : "";
},
// internal only, use is(".class")
has: function( t, c ) {
t = t.className || t;
// escape regex characters
c = c.replace(/([/.///+/*/?/[/^/]/$/(/)/{/}/=/!/</>/|/:])/g, "http://$1");
return t && new RegExp("(^|//s)" + c + "(//s|$)").test( t );
}
},
swap: function(e,o,f) {