JS——坑2(函数不调用不执行,闭包)

来源:互联网 发布:2015年淘宝女装排行榜 编辑:程序博客网 时间:2024/05/18 03:41
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button>one</button><button>two</button><button>three</button><button>four</button><script>var btns = document.getElementsByTagName("button");for(var i=0;i<btns.length;i++){btns[i].onclick = function(){ //函数定义alert(i+1); //都是5!!!!!!}}//注:函数不调用不执行!!!!!//解决方案:闭包</script></body></html>

解决:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button>one</button><button>two</button><button>three</button><button>four</button><script>var btns = document.getElementsByTagName("button");function find(num) {  //factoryreturn function(){alert(num+1);}}for(var i=0;i<btns.length;i++){btns[i].onclick = find(i);}</script></body></html>


另外一个例子:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><script>function fun(){for(var i=0,arr=[];i<3;i++){arr[i] = function(){console.log(i);} //定义函数}return arr;}var funs = fun();console.log(funs);funs[0](); //调用函数 输出3  funs[0] = function(){console.log(i);}funs[1](); //调用函数     3funs[2](); //调用函数     3</script></body></html>



阅读全文
0 0