为什么这个变量没有在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函数内。
上下文成为window
的自setTimeout
是window
的方法。
$('#text_comment').live('keypress', function() {
var el = this;
setTimeout(function() {
var string = $(el).val();
alert(string);
}, 500);
});
如果保存以这种方式EL中引用你可以依靠它,而不是this
而且也,你可以使用,因为那里有el.value
没有必要把它包在jQuery和做内部完全相同的东西通过.val()
太棒了!感谢您的快速响应。接受它时,让我 – 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);
});
也谢谢你,你的答案是伟大的 – 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);
});
您要关闭'textarea'用'div' – 2011-06-15 06:15:57