代碼如下:
<!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">
<title>Each 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>