【问题标题】:Why does this variable not set in a setTimeout function?为什么这个变量没有在 setTimeout 函数中设置?
【发布时间】:2011-09-15 06:33:30
【问题描述】:
我有一个基本的文本区域:
<textarea id='text_comment'></div>
我有这个功能:
$('#text_comment').live('keypress', function() {
setTimeout(function() {
string = $(this).val();
alert(string);
}, 500);
});
它应该提醒文本区域中的值,但它什么也不提醒。
我希望它在 500 毫秒后获取 textarea 的值,但如果它在 setTimeout 函数内部,它似乎不会设置变量。
【问题讨论】:
标签:
javascript
jquery
jquery-selectors
settimeout
jquery-events
【解决方案1】:
上下文变成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() 执行完全相同的操作
【解决方案2】:
this 的值在传递给 setTimeout 的函数内部发生变化。这样做:
$('#text_comment').live('keypress', function() {
var self = this
setTimeout(function() {
string = $(self).val();
alert(string);
}, 500);
});
【解决方案3】:
this 的值取决于当前函数的调用方式。传递给setTimeout 的函数与事件处理函数不同,所以this 的值不同。
先复制this。
$('#text_comment').live('keypress', function() {
var that = this;
setTimeout(function() {
string = $(that).val();
alert(string);
}, 500);
});
【解决方案4】:
因为回调不是在keypress事件的范围内运行,而是在window的全局范围内运行。
复制对局部变量的引用,使其包含在闭包中:
$('#text_comment').live('keypress', function() {
var element = this;
window.setTimeout(function() {
var string = $(element).val();
alert(string);
}, 500);
});
【解决方案5】:
当 'keypress' 事件被触发时,函数中this 的值将是textarea 对象。但是当setTimeout中的函数运行时(500毫秒后),this的值已经变成了别的东西(可能是window对象)
将您的代码更改为:
$('#text_comment').live('keypress', function() {
var textarea = this;
setTimeout(function() {
string = $(textarea).val();
alert(string);
}, 500);
});