【 tulaoshi.com - Web开发 】
代码如下:
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
html
head
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"
titleEach Document/title
script type="text/javascript"
(function(){ //创建一个自执行函数
function _$(el){ //声明一个类
this.elements = []; //用于保存DOM元素的引用
for (var i = 0; i el.length; i++) {
var element = el[i];
if (typeof element == string ) {
element = document.getElementById(element);
}
this.elements.push(element);
}
}
_$.prototype = {
each: function(fn){
for (var i = 0; i this.elements.length; i++) {
fn.call(this, this.elements[i]); //第二个参数是fn函数的参数
}
},
setStyle: function(prop, val){
var that = this;
this.each(function(el){ //注意参数的设置
el.style[prop] = val;
});
return this;
}
}
window.$ = function(){
return new _$(arguments);
};
})();
window.onload = function(){
$("p", "p2").setStyle("color", "red");
}
/script
/head
body
p id="p"
Hello world
/p
p id="p2"
Welcome.
/p
/body
/html