2013-10-08 63 views
0

有人可以告诉我我在哪里出错,我已经在Firefox和Chrome中测试过它,它现在可以正常工作在IE8中。setTimeOut IE8中的参数不起作用

 setTimeout(function(it) { 
      x = $('.menuheader:first-child').position().left; 
      w = $('.menuheader:first-child').width(); 
      p = x + w + 16; 
      $(it).next().css('left', p); 
      $(it).next().show(); 
     }, 200, this); 

也试过......

 function showmenu(it){ 
      x = $('.menuheader:first-child').position().left; 
      w = $('.menuheader:first-child').width(); 
      p = x + w + 16; 
      $(it).next().css('left', p); 
      $(it).next().show(); 
     } 

     window.setTimeout(function() { 
      showmenu(this) 
     }, 200); 
+0

在IE8任何错误? –

+0

重复的http://stackoverflow.com/questions/7007364/settimeout-issue-in-ie8 – user568109

+0

重复也没有为我工作。 –

回答

1

正确的传统方式“传递参数“到一个不能接受它们的函数是关闭的:

var that = this; 
setTimeout(function(){ doStuff(that);}, 200); 

function doStuff(it) { 
    x = $('.menuheader:first-child').position().left; 
    w = $('.menuheader:first-child').width(); 
    p = x + w + 16; 
    $(it).next().css('left', p); 
    $(it).next().show(); 
} 

一个较新的替代(无填充工具不与IE8兼容):

setTimeout(doStuff.bind(null, this), 200); 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

+0

我得到的错误:SCRIPT5009:'它'是未定义的 –

+0

是的,现在更好,那里的'那'。 –

+0

是的,你的第二次尝试不起作用,因为当函数被调用时,JS通常会改变'this'。这就是为什么当你通过闭包传递'this'时你需要给它一个新的名字。 – Tibos

1

我从来没有发现setTimeout参数是特别可靠的,所以我只是这样做:

var it = this; 
setTimeout(function() { ... }, 200);