![](/img/trans.png)
[英]jQuery .keyPress() - How to get value of input which triggered event?
[英]How can I get the NEW value of an HTML text input during a keypress event via jQuery?
我只能在沒有新按下的鍵的情況下檢索值。 使用keyup
事件不是一種選擇,因為如果用戶不釋放鍵,它不會觸發。 這很重要,因為我想對每一個按鍵都采取行動。
將舊值與可從事件參數訪問的keyCode
相結合也是不可接受的,因為不能保證用戶會在文本框中鍵入字符串的末尾。
將處理程序代碼包裝在setTimeout(function() { ... }, 0)
。
在value
更新后,這將在下一個消息循環中執行代碼。
可以計算出按鍵后的值。 這在非 IE 瀏覽器中很容易,在 IE 中更棘手,但以下內容可以做到:
document.getElementById("your_input").onkeypress = function(evt) {
var val = this.value;
evt = evt || window.event;
var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode;
if (charCode) {
var keyChar = String.fromCharCode(charCode);
var start, end;
if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
start = this.selectionStart;
end = this.selectionEnd;
} else if (document.selection && document.selection.createRange) {
// For IE up to version 8
var selectionRange = document.selection.createRange();
var textInputRange = this.createTextRange();
var precedingRange = this.createTextRange();
var bookmark = selectionRange.getBookmark();
textInputRange.moveToBookmark(bookmark);
precedingRange.setEndPoint("EndToStart", textInputRange);
start = precedingRange.text.length;
end = start + selectionRange.text.length;
}
var newValue = val.slice(0, start) + keyChar + val.slice(end);
alert(newValue);
}
};
這是一個可能有效的想法。 使用按鍵並在該點存儲 val,以便您始終可以將當前值與最后一個值進行比較並找出字符串中的差異。 不同之處在於按下的鍵。
一種方法是將字符串轉換為數組並比較兩個數組,就像他們在這里做的那樣: JavaScript 數組差異
從來沒有嘗試過這樣的事情,所以它可能不可行,但可能值得一試。
我有一個使用 TAB 鍵的特定案例,它更改了 keyUp 中的 e.target,所以這就是解決方案 - 綁定到容器元素,在 keyDown 處理程序中獲取目標輸入,訂閱 keyUp 並讀取值。
$("#container").keydown(function (e) {
//here you decide whether to handle the key event, and grab the control that sent the event
var myInput = e.target;
$("#container").one('keyup', function() {
console.log(myInput.val());
// do smth here
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.