DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> 模仿jQuery each函數的鏈式調用
模仿jQuery each函數的鏈式調用
編輯:JQuery特效代碼     
代碼如下:
<!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>

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved