Javascript jquery(或纯js)模拟按下回车键进行测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3276794/
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 03:59:15  来源:igfitidea点击:

jquery (or pure js) simulate enter key pressed for testing

javascriptjquerytestingmocking

提问by morgancodes

What the best way to simulate the user pressing "enter"? $(element).keypress() doesn't seem to allow me to pass in the actual key that was pressed.

模拟用户按“输入”的最佳方法是什么?$(element).keypress() 似乎不允许我传入实际按下的键。

This is for unit testing.

这是用于单元测试。

回答by redsquare

Demo Here

演示在这里

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

回答by Fabien Sa

For those who want to do this in pure javascript, look at:

对于那些想要在纯 javascript 中执行此操作的人,请查看:



Outdated:

过时

You can do something like (here for Firefox)

您可以执行类似的操作(此处适用于 Firefox)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);


Updated:

更新

As Joe comment it, KeyboardEventis now the standard.

正如乔评论的那样,KeyboardEvent现在是标准。

Same example to fire an enter (keyCode 13):

触发输入的相同示例(keyCode 13):

const ke = new KeyboardEvent("keydown", {
    bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);

You can use this pagehelp you to find the right keyboard event.

您可以使用此页面帮助您找到正确的键盘事件。