为什么这个变量没有在setTimeout函数中设置?

问题描述:

嘿程序员,为什么这个变量没有在setTimeout函数中设置?

我有一个基本的textarea:

<textarea id='text_comment'></div> 

我有这样的功能:

$('#text_comment').live('keypress', function() { 

    setTimeout(function() { 
    string = $(this).val();   

     alert(string); 
    }, 500); 

}); 

应该提醒的是在textarea的价值,但它什么也没有提醒。

我希望它能在500ms后得到textarea的值,但它似乎没有设置变量,如果它在setTimeout函数内。

+0

您要关闭'textarea'用'div' – 2011-06-15 06:15:57

上下文成为window的自setTimeoutwindow的方法。

$('#text_comment').live('keypress', function() { 

    var el = this; 

    setTimeout(function() { 
     var string = $(el).val();   

     alert(string); 
    }, 500); 

}); 

如果保存以这种方式EL中引用你可以依靠它,而不是this

而且也,你可以使用,因为那里有el.value没有必要把它包在jQuery和做内部完全相同的东西通过.val()

+0

太棒了!感谢您的快速响应。接受它时,让我 – TaylorMac 2011-06-15 06:16:34

this的值在传递给setTimeout的函数内发生了变化。像这样做:

$('#text_comment').live('keypress', function() { 

    var self = this 

    setTimeout(function() { 
    string = $(self).val();   

     alert(string); 
    }, 500); 

}); 
+0

也谢谢你,你的答案是伟大的 – TaylorMac 2011-06-15 06:16:52

当“按键​​”事件被激发的this在函数的值会textarea对象。但是当setTimeout运行该功能(后500毫秒),中this值已改为别的东西(也许window对象)

你的代码更改为:

$('#text_comment').live('keypress', function() { 

    var textarea = this; 
    setTimeout(function() { 
    string = $(textarea).val();   

     alert(string); 
    }, 500); 

}); 

this值取决于关于如何调用当前函数。您传递给setTimeout的函数与事件处理程序的功能不同,因此this的值不同。

首先制作this的副本。

$('#text_comment').live('keypress', function() { 
    var that = this; 
    setTimeout(function() { 
    string = $(that).val();   
     alert(string); 
    }, 500); 

}); 

由于回调并不在keypress事件的范围运行,但在全球范围内window

复制引用到本地变量,因此它被包括在封闭:

$('#text_comment').live('keypress', function() { 

    var element = this; 

    window.setTimeout(function() { 
    var string = $(element).val();   
    alert(string); 
    }, 500); 

});