[英]JavaScript: How to get value of sender input element from keyup event?
我需要捕獲keyup事件以在用戶輸入輸入時提供實時驗證(僅當輸入失去焦點時才會觸發更改事件)。
我無法獲取觸發evnt的輸入的編輯值。
該代碼還在定時器上運行,以防止在用戶鍵入時多次調用(每500毫秒觸發一次)。
我有幾個輸入類“priceinput”並附加到每個的keyup事件,如下所示:
<script language="javascript" type="text/javascript">
var timer;
$(document).ready(function()
{
$(".priceinput").each(function()
{
$(this).keyup(function(e)
{
clearTimeout(timer);
timer = setTimeout(function()
{
//how to get the value of the input element that was changed?
var value = ???;
$.getJSON('/Validator/IsValidInput', { input: value },
function(response)
{
//indicate if input is correct
});
}, 500);
});
});
});
</script>
為了獲取發送者輸入值,我嘗試了$(this).val
, this.val()
, e.target.val()
但似乎沒有工作。
如何獲取發件人輸入的值?
問題是在你的超時函數中,你已經丟失了對輸入元素的“this”引用。 嘗試這樣的事情:
$('.priceinput').keyup(function(e) {
var $input = $(this);
clearTimeout(timer);
timer = setTimeout(function() {
var value = $input.val();
$.getJSON( ... );
}, 500);
});
在Internet Explorer中,它應該是event.srcElement
,在Firefox event.target
。
或者嘗試event.toElement
和event.relatedTarget
。
(當然,將它們與.value
或.val()
結合起來)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.