我只能在没有新按下的键的情况下检索值。不能使用keyup
事件,因为如果用户不释放键,则不会触发。这很重要,因为我想对每个按键进行操作。
也不接受将旧值与事件的参数可以到达的keyCode
结合起来,因为不能保证用户将在文本框中键入字符串的末尾。
可以计算出按键后的值。在非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);
}
};
将处理程序代码包装在setTimeout(function() { ... }, 0)
中。
[value
更新后,它将在下一个消息循环中执行代码。
这是一个可行的想法。使用按键并存储该点的val,以便您始终可以将当前值与最后一个值进行比较,并找到字符串中的差异。区别在于所按下的键。
执行此操作的一种方法是将字符串转换为数组,然后像在这里一样比较两个数组:JavaScript array difference
从未尝试过类似的操作,因此它可能不可行,但值得一试。
我有一个使用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
});
});