简体   繁体   English

在 Javascript 中手动操作输入时,如何确保触发键盘事件?

[英]How do I make sure a keyboard event is firing when manually manipulating an input in Javascript?

I am on the site RedBubble.com and want to simulate someone typing into the search box.我在 RedBubble.com 网站上,想模拟有人在搜索框中输入内容。 When someone types something in there is a window that shows data like search suggestions etc...当有人在其中输入内容时,会有一个 window 显示搜索建议等数据......

I open up my console.我打开我的控制台。 I type in the following in:我输入以下内容:

let searchbar = document.querySelector('input[name="query"]');
searchbar.value = 'Cat';

This results in the search bar showing the word cat but it does not produce the focus or fire the window that typically shows up if you click on the search box.这会导致搜索栏显示单词 cat,但它不会产生焦点或触发 window,如果您单击搜索框,通常会出现这种情况。

On google I was able to do something similar with the search bar and then get it to show the keyword suggestions when using code like this:在谷歌上,我可以对搜索栏做类似的事情,然后在使用这样的代码时让它显示关键字建议:

searchbar.click();

But I am missing something when trying to do the same on the RedBubble site within my console.但是当我尝试在我的控制台中的 RedBubble 网站上做同样的事情时,我错过了一些东西。

This is what I am hoping to see:这是我希望看到的: 搜索栏弹出框的图片

The suggestion dialog window is triggerd by a focus event on the <input name="query"> element.建议对话框 window 由<input name="query">元素上的focus事件触发。 You can simulate that event by creating and dispatching your own event.您可以通过创建和调度您自己的事件来模拟该事件。

const focusEvent = new Event('focus');
document.querySelector('input[name="query"]').dispatchEvent(focusEvent);

Though, it does not seem possible to show results based on the value of the input.但是,似乎不可能根据输入的value显示结果。 That logic seems to be dictated by the logic in the React app.该逻辑似乎是由 React 应用程序中的逻辑决定的。

That's because the click event is not on the input but instead on the search icon button,那是因为点击事件不在输入上,而是在搜索图标按钮上,

You need to do:你需要做:

document.querySelector('button[type=submit]').click()

you can add this:你可以添加这个:

searchbar.addEventListener("input", function(){
    //do something
});

to actively listen for inputs积极倾听输入

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

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