标签:
var tag = function (tag){ return document.getElementsByTagName(tag); } var id = function (id){ return document.getElementById(id); } var className = function (className){ return document.getElementsByClassName(className); }
这是html部分代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> div, p { width: 200px; height:50px; border:1px dashed red; margin: 10px 0; } </style> </head> <body> <div></div> <div></div> <p></p> <p></p> </body>
//例如给div盒子添加背景色我们可能会这么做 var divs = tag(‘div‘); var each = function (arr){ for(var i = 0;i< arr.length;i++){ arr[i].style.backgroundColor = ‘pink‘; } } each(divs); //也可能会这么做 var list = tag(‘div‘); var each = function (arr,fn){ for(var i = 0;i<arr.length;i++){ if(fn.call(arr[i],i,arr[i]) === false ){//等于false时,终止循环 break; } } } each(list,function(){ this.style.backgroundColor = ‘yellow‘; })
//上式的fn.call(arr[i],i,arr[i]) === false,下面函数也用到这种调用方式,可以做下比较 var arr = [ 1, 2, 3, 4, 3, 5]; var each = function ( arr, fn ) { for ( var i = 0; i < arr.length; i++ ) { if ( fn( i, arr[ i ] ) === false ) { break; } } }; var index = -1; each( arr, function ( i, v ) { if ( v === 3 ) { index = i; return false;//若是break 遍历不会终止 直到遍历完 } } ); console.log( index );//2
/*var tag = function (tag){
return document.getElementsByTagName(tag);
}*/
//以上这种写法的缺点是每次获得元素后又要返回,以至于造成浏览器性能的损耗
//为了简化开发,可以将获得的数组合并到一个数组中,这也是jq中所用到的
var getTag = function ( tag, results ) { results = results || []; results.push.apply( results, document.getElementsByTagName( tag ) ); return results; }; var list = getTag(‘div‘); list = getTag(‘p‘,list);//如果再获得p标签,可以这么写 var each = function (arr,fn){ for(var i = 0;i<arr.length;i++){ if(fn.call(arr[i],i,arr[i]) === false ){//等于false时,终止循环 break; } } } /*each(list,function(){ this.style.backgroundColor = ‘lightgreen‘; })*/ each(getTag(‘p‘,getTag(‘div‘)),function(){ this.style.backgroundColor = ‘lightgreen‘; })
标签:
原文地址:http://www.cnblogs.com/goweb/p/5373156.html