0

嘿程序員,爲什麼這個變量沒有在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

回答

5

上下文成爲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

1

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

0

當「按鍵​​」事件被激發的this在函數的值會textarea對象。但是當setTimeout運行該功能(後500毫秒),中this值已改爲別的東西(也許window對象)

你的代碼更改爲:

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

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

     alert(string); 
    }, 500); 

}); 
1

this值取決於關於如何調用當前函數。您傳遞給setTimeout的函數與事件處理程序的功能不同,因此this的值不同。

首先製作this的副本。

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

}); 
1

由於回調並不在keypress事件的範圍運行,但在全球範圍內window

複製引用到本地變量,因此它被包括在封閉:

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

    var element = this; 

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

}); 
相關問題