Javascript 如何在文本字段上触发退格键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6921111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:46:17  来源:igfitidea点击:

How to trigger backspace on a textfield?

javascriptjquerytriggerskeycodebackspace

提问by odle

Say I have this:

说我有这个:

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

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:

我如何可能使用 trigger() 和键代码在该 textarea 上触发退格键。退格的代码是 8。我不是在找这个:

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

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

我需要模拟某人实际按下键盘上的“退格”键。谢谢

回答by rkw

You can create a keydown event:

您可以创建一个 keydown 事件:

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

Then trigger it in your textarea:

然后在你的 textarea 中触发它:

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

Update:

更新:

After doing some more research and testing, I realize that this solution does NOTsimulate a naturalkeypress 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.

做一些更多的研究和测试后,我意识到,这个解决方案确实不是模仿自然的HTML元素上的按键事件。此方法仅触发 keydown 事件,它不会复制用户进入元素并按下该键。

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

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

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.

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

回答by Jose Adrian

I found this:

我找到了这个:

http://forum.jquery.com/topic/simulating-keypress-events(answer number 2).

http://forum.jquery.com/topic/simulating-keypress-events(答案 2)。

Something like this should work, or at least give you an idea:

这样的事情应该有效,或者至少给你一个想法:

<div id="hola"></div>

$(function(){
    var press = jQuery.Event("keyup");
    press.ctrlKey = false;
    press.which = 40;

    $('#hola').keyup(function(e){
        alert(e.which);
    })
   .trigger(press); // Trigger the event
});

Demo: http://jsfiddle.net/qtPcF/1/

演示:http: //jsfiddle.net/qtPcF/1/

回答by Gibolt

You shouldn'tbe forcing key events in js. Try simulating the character removal instead.

应该在 js 中强制执行关键事件。尝试模拟字符删除。

const start = textarea.selectionStart - 1;
const value = textarea.value;
const newValue = value.substr(0, start) + a.substr(start);
textarea.value = newValue;

Or if you just want the event, instead call the handler directly, rather than forcing the event. This is too hacky.

或者,如果您只想要事件,则直接调用处理程序,而不是强制事件。这太坑了。