JavaScript keypress事件获取textarea的结束值 [英] JavaScript keypress event get end value of textarea

查看:135
本文介绍了JavaScript keypress事件获取textarea的结束值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能在 keypress 事件中获得最终结果?
目前,我正在使用 keyup ,因为在用户在texteara中完成文本编辑后,它已被激活,但我已经写了使用Mootools库执行类似操作的方法:

I was wondering if it were possible to get the end result in the keypress event? Currently, I am using the keyup because it is activated after the user has done text editing in a texteara, but I have written a method that does something similar using the Mootools library:

input.addEvent("keypress", function (input) {
    var previous_result = this.value;
    var end_result = this.value + input.key;
});

然而,这种方法在处理退格键等特殊键时很糟糕,或者如果用户选择使用 CTRL + a && Backspace 在这种情况下,input元素的值不会是空字符串。

However, this method is horrible when dealing with special keys such as backspace, or if the user chooses to use CTRL + a && Backspace in which case the value of the input element would not be "an empty string".

我很好奇因为我观察过Google的搜索引擎发送XMLHttpRequest并在 keyup 事件触发之前改变页面
此外,他们使用的输入设法克服了删除整个文本的问题,同时仍然享受 keypress 的奢侈。

I'm curious because I have observed Google's search engine sending XMLHttpRequest AND mutating the page before the keyup event triggered. Additionally, the input they use manages to overcome my problem of removing entire text while still enjoying the luxury of keypress.

谢谢!

推荐答案

这将使其有效:

input.addEvent( "keypress", function ( input ) {    
    setTimeout(function () {
        input.value // returns the updated value
    }, 0 );    
});

现场演示: http://jsfiddle.net/yQQ5P/ (我使用内置API,因为我不知道Mootools)

Live demo: http://jsfiddle.net/yQQ5P/ (I use built-in API, as I don't know Mootools)

因此,您使用零超时作为收益。这为浏览器的UI线程提供了更新输入值的机会。

So, you use a zero-timeout which acts as a yield. This gives the browser's UI thread an opportunity to updated the input's value.

这篇关于JavaScript keypress事件获取textarea的结束值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆