each()方法能使DOM循環結構簡潔,不容易出錯。each()函數封裝了十分強大的遍歷功能,使用也很方便,它可以遍歷一維數組、多維數組、DOM, JSON 等等
在javaScript開發過程中使用$each可以大大的減輕我們的工作量。
下面提一下each的幾種常用的用法
var arr1 = [ "aaa", "bbb", "ccc" ];
$.each(arr1, function(i,val){
alert(i);
alert(val);
});
alert(i)將輸出0,1,2
alert(val)將輸出aaa,bbb,ccc
each處理二維數組
var arr2 = [['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']] $.each(arr2, function(i, item){ alert(i); alert(item); });
arr2為一個二維數組,item相當於取這二維數組中的每一個數組。
item[0]相對於取每一個一維數組里的第一個值
alert(i)將輸出為0,1,2,因為這二維數組含有3個數組元素
alert(item)將輸出為 ['a', 'aa', 'aaa'],['b', 'bb', 'bbb'],['c', 'cc', 'ccc']
對此二位數組的處理稍作變更之后
ar arr = [['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']] $.each(arr, function(i, item){ $.each(item,function(j,val){ alert(j); alert(val); }); });
alert(j)將輸出為0,1,2,0,1,2,0,1,2
var obj = { one:1, two:2, three:3}; $.each(obj, function(key, val) { alert(key); alert(val); });
這里alert(key)將輸出one two three
alert(val)將輸出one,1,two,2,three,3
這邊為何key不是數字而是屬性呢,因為json格式內是一組無序的屬性-值,既然無序,又何來數字呢。
而這個val等同於obj[key]
js中each實現,首先感謝豪情哥提供的跟隨對聯廣告實例,讓我有機會知道這么多我欠缺的知識點。代碼里有我個人的理解標注了解釋。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>跟隨對聯廣告-豪情</title> <meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> <style type="text/css"> *{margin:0;padding:0;} body{ font:12px/1.125 Microsoft YaHei; background:#fff; } ul,li{list-style:none;} a{text-decoration:none;} .wrap{width:600px;height:350px;margin:10px auto;border:1px solid #ccc;} .inner{padding:15px;} .clearfix{overflow:hidden;_zoom:1;} .none{display:none;} .banner{width:100px;height:300px;position:absolute;top:200px;} .banner:nth-child(1){left:100px;} .banner:nth-child(2){right:100px;} </style> </head> <body> <div style="height:3000px"></div> <div style="display:none;"> <div id="div" style="width:100px;height:200px;background:#000;"></div> <button id="btn">test</button> </div> <script> (function(){ //dog是一個方法類 就是一個簡短的自定義的類jquery庫 var dog = { $ : function(id){ return document.querySelector(id); }, tpl : function(html, data){ return html.replace(/{{(\w+)}}/g, function(item, a){ return data[a]; }); }, pos : function(obj, attr){ if(obj){ return obj.getBoundingClientRect()[attr]; } else { alert('對象不存在!'); } }, viewSize: function(){ var de = document.documentElement; var doc = document; return { 'width': (window.innerWidth || (de && de.clientWidth) || doc.body.clientWidth), 'height': (window.innerHeight || (de && de.clientHeight) || doc.body.clientHeight) }; }(), on: function(el, type, handler){ el.addEventListener(type, handler, false);//監聽事件 }, off: function(el, type, handler){ el.removeEventListener(type, handler, false);//移除監聽 }, css : function(obj, attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; } else { return getComputedStyle(obj, false)[attr]; } }, act : function(obj, attr, target){ var that = this; clearInterval(obj.timer); obj.timer = setInterval(function(){ var stop = true; var cur = parseInt(that.css(obj, attr)); var speed = (target - cur) / 8; speed = speed < 0 ? Math.ceil(speed) : Math.floor(speed); if(target != speed){ stop = false; } obj.style[attr] = speed + cur + 'px'; if(stop){ clearInterval(obj.timer); } }, 55); }, //自己實現each方法 each : function(arr, callback){//數組,回調函數 arr大約等於opt if(Array.isArray(arr)){ for(var i = 0, l = arr.length; i < l; i++){ //出現false即出錯情況下出現 if(callback.call(arr[i], i, arr[i++]) == false){//元素對象存在 i相當於下面function(i,m)中的i,arr[i++]相當於m break; } } } else { for(var name in arr){ if(callback.call(arr[name], name, arr[name]) == false){//元素對象存在 name相當於下面function(i,m)中的i,arr[name]相當於m break; } } } }, create : function(opt){//傳入一個對象 var el = document.createElement(opt.tag || 'div'); this.each(opt, function(i, m){ el[i] = this;// }); return el; } } function Adv(){ var args = arguments[0]; for(var i in args){ this[i] = args[i]; } this.init(); } Adv.prototype = { init : function(){ this.render(); this.bind(); }, render : function(){ var div = dog.create({ className : 'out'}), a = dog.create({ className : 'banner'}), b = null; a.innerHTML = this.tpl; b = a.cloneNode(true); div.appendChild(a); div.appendChild(b); document.body.appendChild(div); this.a = a; this.b = b; }, bind : function(){ var that = this, doc = document, scrollTop = 0, t = 0; //調用dog類 dog.on(window, 'scroll', function(){//監聽scroll事件 scrollTop = doc.documentElement.scrollTop || doc.body.scrollTop; t = scrollTop + (doc.documentElement.clientHeight - that.a.offsetHeight) / 2; dog.act(that.a, 'top', t); dog.act(that.b, 'top', t); }); }, getDom : function(){ } } var defaults = { id : 'dialog', tpl : '<img src="images/ad.jpg" alt="">' } new Adv(defaults); }()); </script> </body> </html>
自己做到demo理解
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>test</title> </head> <body> <div id="xid">dddddddddddddd</div> </body> <script type="text/javascript" language="javascript"> (function(){ var test={ $:function(id){ return document.querySelector(id); }, xx:function(obj){ //alert(obj); var obd= document.getElementById(obj); // obd.innerHTML="wo test"; obd.style.backgroundColor='red'; } } function demo(){ var args = arguments[0]; for(var i in args){ this[i] = args[i]; } this.init(); } demo.prototype = { init : function(){ this.render(); }, render : function(){ var that =this; // alert(that.id)); var b= test.xx(that.id); } } var test2={ id:'xid' }; new demo(test2); })(); </script> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>test</title> </head> <body> <div id="xid" style="width:200px; height:230px;">dddddddddddddd</div> </body> <script type="text/javascript" language="javascript"> //HTML DOM querySelector() 關鍵是這個方法的語法和用法 (function(){ var test={ $:function(id){ return document.querySelector(id); }, xx:function(){ //that.abc() //alert(that.id); //var obd= document.getElementById(that.id); // obd.innerHTML="wo test"; //obd.style.backgroundColor='red'; }, css : function(obj, attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; } else { return getComputedStyle(obj, false)[attr]; } }, } function demo(){ var args = arguments[0]; for(var i in args){ this[i] = args[i]; } this.init(); } demo.prototype = { init : function(){ this.render(); }, render : function(){ var that=this; var target=test.$("#"+that.id); target.style.backgroundColor='red'; alert(test.css(target,'width')); } } var dddd={ id:'xid' }; new demo(dddd); })(); </script> </html>
由於對js了解甚少,又不知道從哪些地方入手,於是打算從理解+模仿來學習。希望有所獲。
模仿學習案例鏈接:http://www.kancloud.cn/jikeytang/qq/81141
