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);
});