如何在文本字段上触发退格键? [英] How to trigger backspace on a textfield?

查看:126
本文介绍了如何在文本字段上触发退格键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个:

<textarea id="myarea">Hello</textarea>

我可能如何使用trigger()和键代码在该文本区域上触发退格键.退格代码为8. 而且我不是在寻找这个东西:

How would i trigger backspace on that textarea possibly using trigger() and key codes. The code for backspace is 8. And i am not looking for this:

$('#myarea').val( $("myarea").val().slice(0,-1) );

我需要模拟实际按下键盘上的退格"键的人. 谢谢

I need to simulate someone actually pressing the 'backspace' key on their keyboard. Thanks

推荐答案

您可以创建按键事件:

var e = jQuery.Event("keydown", { keyCode: 20 });

然后在您的文本区域中触发它:

Then trigger it in your textarea:

$("#myarea").trigger( e );

更新:

经过更多研究和测试后,我意识到此解决方案不会模拟HTML元素上的自然键按下事件.此方法仅触发keydown事件,不会复制用户进入元素并按该键的操作.

After doing some more research and testing, I realize that this solution does NOT simulate a natural keypress event on the HTML element. This method only triggers the keydown event, it does not replicate the user going into the element and pressing that key.

要模拟进入该文本框并按下该键的用户,您必须创建一个

To simulate the user going into that textbox and pressing that key, you would have to create a dispatch event

也不全局支持调度事件.最好的选择是触发keydown事件,然后按预期更新文本区域.

The dispatch event is also not globally supported. Your best bet would be to trigger the keydown event and then update the text area as intended.

这篇关于如何在文本字段上触发退格键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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