无论是window.setTimeout还是window.setInterval,在使用函数名作为调用句柄时都不能带参数。 


先看一个简单的代码: 


Javascript代码  setTimeOut传参数_传参数


  1. function show(){      
  2.     alert("Hello World");  
  3. }  
  4. setTimeout(show,1000);  




这段代码的效果是在1秒后显示hello world,但是如果改成 


setTimeOut(show(),1000); 


就会立即显示,达不到延时的效果了。但是如果加上引号就可以了。如: 


setTimeOut("show()",1000); 


就可以了。但是如果带上参数的话,还是不行比如: 


setTimeOut("show(name)",1000) 


这时就了一个比较的方法,就是再写个函数,该函数返回一个不带参数的函数,具体如下: 


Javascript代码  setTimeOut传参数_传参数


  1. <script language="javascript">  
  2.     function show(name)  
  3.     {alert("Hello World:" + name);}  

  4.     function _show(name)  
  5.     {  
  6.         return function()  
  7.         {  
  8.             show(name);  
  9.         }  
  10.     }  
  11.     setTimeout(_show(name),1000);  
  12. </script>  






setTimeout传参数问题,弄了很久,终于解决了,O(∩_∩)O哈! 





view plain 

Javascript代码  setTimeOut传参数_传参数


  1. function timeClick(obj)    
  2.        {    
  3.         //   var obj=document.getElementById('');    
  4.            obj.style.backgroundColor=&quot;gray&quot;;    
  5.            obj.onclick=function(){ return false;};    
  6.            setTimeout(function(){resetbgColor(obj);},3000);    
  7.        }    

  8.        function resetbgColor(obj)    
  9.        {    
  10.          //  var obj=document.getElementById('');    
  11.            obj.style.backgroundColor=&quot;&quot;;    
  12.         //   $('#'+'').click(timeClick);    
  13.       //  debugger;    
  14.            obj.onclick=function(){    
  15.                timeClick(this);    
  16.            };    
  17.        }    




          我发现这句还真是万能啊,太服了, function(){ method(param);} 


          这里两个地方都用到了,解决了我的所有问题,1.setTimeout传参数 2.动态设置onclick事件 


         setTimeout(function(){resetbgColor(obj);},3000); 



          obj.onclick=function(){ 
                timeClick(this); 
            };