回调函数(就是一个名字)
原理:函数可以作为参数传递 函数也是一种数据类型 特殊在可以加()执行 .
作用:当自身执行完 还想在执行另一个函数 使用回调函数
可以有 也可以没有
例子
当同一个函数客户要求的效果不同时,不用在一个函数改来改去,要那个效果就在回调函数写那个. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Author" content=" "> <title>Document</title> <style type="text/css"> *{margin: 0;padding: 0;} a{text-decoration: none;} ul,li{list-style: none;} body{font-size: 14px;font-family: "微软雅黑";} div{width: 100px;height: 100px;background: red;margin: 10px auto;text-align: center;line-height: 100px;} </style> </head> <body> <div id="box1">点我</div> <div id="box2">点我</div> <div id="box3">点我</div> <script type="text/javascript"> var box1 = document.getElementById("box1"); var box2 = document.getElementById("box2"); var box3 = document.getElementById("box3"); // box1.onclick = function(){ // this.style.width = "150px"; // this.style.height = "150px"; // this.style.background = "green"; // }; //效果1 clickMe("box1",function(a){ a.style.width = "150px"; }); //效果2 clickMe("box2",function(a){ a.style.height = "200px"; a.style.background = "yellow"; a.style.lineHeight = "200px"; }); //效果3 clickMe("box3",function(a){ window.location.href = "http://www.baidu.com"; }); //封装下 function clickMe(elemnt,callBack){ var boxDom = document.getElementById(elemnt); boxDom.onclick = function(){ //if(callBack)callBack(this); callBack && callBack(this); }; } </script> </body> </html>处理数据例子
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Author" content=" "> <title>Document</title> <style type="text/css"> *{margin: 0;padding: 0;} a{text-decoration: none;} ul,li{list-style: none;} body{font-size: 14px;font-family: "微软雅黑";} </style> </head> <body> <script type="text/javascript"> var num = [1,2,3,40,20];//一个数组 //取反 [-1,-2,-3,-40,-20]; function negative(n){ return -n; } //平方 function square(n){ return n*n; } alert(fn(num,negative)); alert(fn(num,square)); function fn(num,callBack){ var result = []; for(var i=0;i<num.length;i++){ if(callBack){ result[i] = callBack(num[i]); } } return result; } // $(function(){ // $("#box").animate({}, speed,function(){ // }); // }) </script> </body> </html>