0

它以我拥有此代码的方式返回未定义的 var "el"

$('.element').each(function(){
    var el = $(this);
    setTimeout(function(el) {
        el.css({ marginTop: -100 });
    }, 550);
    $(window).resize(function(el) {
        setTimeout(function(el) {
            el.css({ marginTop: -100 }); //this is where el is undefined
        }, 550);            
    })
});

知道我在做什么错吗?

4

3 回答 3

3

我认为这是因为el作为函数参数。尝试删除它们。

$('.element').each(function(){
    var el = $(this);
    setTimeout(function() {
        el.css({ marginTop: -100 });
    }, 550);
    $(window).resize(function() {
        setTimeout(function() {
            el.css({ marginTop: -100 }); //this is where el is undefined
        }, 550);            
    })
});

如果我错了,别忘了把我钉在十字架上:P

编辑:只是为了解释发生了什么,functioninresize传递了一个event对象,因此它会覆盖el您设置的变量。Event不是一个jQuery对象,所以你不能css在它上面调用函数。

于 2013-10-03T13:47:27.737 回答
0

el您传递给事件setTimeout和事件的参数resize是不必要的,

工作示例:http: //jsfiddle.net/atg7F/

于 2013-10-03T13:47:02.047 回答
0

您正在覆盖el. 试试这个:

http://jsfiddle.net/Um7Tp/1/

$('.element').each(function(){
    var el = $(this); // this var was overwritten...
    setTimeout(function() { // here
        console.log(el);
        el.css({ marginTop: -100 });
    }, 550);

    $(window).resize(function() { // here
        setTimeout(function() { // and here
            el.css({ marginTop: -100 }); 
            console.log(el);
        }, 550);            
    })
});
于 2013-10-03T13:50:19.577 回答