IE8中的参数的setTimeOut不起作用

时间:2013-10-08 09:40:55

标签: javascript internet-explorer-8

有人可以告诉我这里我出错的地方,我已经在Firefox和Chrome中测试了它,现在只需要它在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);

2 个答案:

答案 0 :(得分:2)

将“传递参数”传递给无法接受它们的函数的正确遗留方法是使用闭包:

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();
}

更新的替代方案(与没有polyfill的IE8不兼容):

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

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

答案 1 :(得分:1)

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

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