简体   繁体   English

JavaScript keypress事件获取textarea的结束值

[英]JavaScript keypress event get end value of textarea

I was wondering if it were possible to get the end result in the keypress event? 我想知道是否有可能在keypress事件中获得最终结果? 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: 目前,我使用的keyup因为用户已完成文本编辑在texteara 它被激活,但我已经写了,做类似使用MooTools的图书馆的东西的方法:

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

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". 但是,这种方法在处理特殊键(如退格键)时非常糟糕,或者如果用户选择使用CTRL + a && Backspace ,则输入元素的值不会是“空字符串”。

I'm curious because I have observed Google's search engine sending XMLHttpRequest AND mutating the page before the keyup event triggered. 我很好奇,因为我观察到Google的搜索引擎发送XMLHttpRequest并触发keyup事件之前改变页面。 Additionally, the input they use manages to overcome my problem of removing entire text while still enjoying the luxury of keypress . 此外,他们使用的输入设法克服了删除整个文本的问题,同时仍然享受keypress的奢侈。

Thanks! 谢谢!

This will make it work: 这将使它工作:

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

Live demo: http://jsfiddle.net/yQQ5P/ (I use built-in API, as I don't know Mootools) 现场演示: http //jsfiddle.net/yQQ5P/ (我使用内置API,因为我不知道Mootools)

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. 这为浏览器的UI线程提供了更新输入值的机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM