仿jQuery.each()方法遍历对象(DOM、 Array、JSON、String)

原创
2013/04/02 11:25
阅读数 1.2K

HTML : 

<span class="p1">A</span>
<span class="p2">B</span>
<span class="p3">C</span>
<span class="p4">D</span>

Javascript:

Object.prototype.each = String.prototype.each = function(fn) { 
	for (var i in this) {
	 	if (this.hasOwnProperty(i)) {  	
			if(typeof(this[i]) == "object") {
				fn(i, this[i]);
			} else { 
				try { 
					if(!this[0].nodeName) fn(i, this[i]);
				}
				catch (e) { 
					fn(i, this[i]);
				}				
			}
		}
	}
}

//遍历DOM对象
var arr = document.getElementsByTagName("span");
arr.each(function(index, obj) {
	console.log(index, obj, "className =>", obj.className);
});

//遍历数组
[2,3,5].each(function(index, obj) {
	console.log(index, "=>", obj);
});

//遍历JSON序列对象
var json = {name : "pandao", job : "2D(Web/UI Designer & Web Developer)", length : [1,2,3,4], dom : {nodeName : "span"}, callback : new Function};
json.each(function(index, obj) {
	console.log(index, "=>", obj);

	//嵌套遍历
	if(typeof (obj) == "object") {
		obj.each(function(i, o) {
			console.log("    ", index+"."+i, "=>", o);
		});
	}
});

//遍历字符串
'<script type="text/javascript">'.each(function(index, str) {
	console.log(index, "=>", str);
});
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部