2013-10-08 53 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);