Posted in Javascript onJuly 22, 2009
<!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>
模仿jQuery each函数的链式调用
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@