【发布时间】:2021-04-09 23:59:23
【问题描述】:
我正在尝试触发以编程方式填充输入的搜索。
虽然找不到明确的 Javascript 示例。 Jquery 不是一个真正的选择,因为我想保持它是一个轻量级的 Chrome 扩展。
发出 'Enter' 事件似乎只是返回一个 true,实际上并没有开始搜索。
HTML
<form id="form">
<input type="text" placeholder="Search Foo" />
</form>
Javascript
const input = document.querySelector(`input[placeholder="Search Foo"]`);
// ^^ targets element successfully
input.value = "this is my search term";
// ^^ adds value to input fine.
input.dispatchEvent(new Event('focus'));
// ^^ appears to focus correctly
input.dispatchEvent(new KeyboardEvent('keyup',{'keyCode': 13}));
// ^^ returns 'true' in console but nothing happens.
const form = document.getElementById("form");
form.submit();
// ^^ triggers a full page refresh, not an 'enter' / submit action.
我已经尝试了一些变体(主要是弃用的 KeyEvents 语法)。
为什么我实际上不能在输入/表单上触发“输入”/提交?
【问题讨论】:
-
你有点击回车搜索数据的功能吗?
-
我认为你应该使用 keypress 或 keyup 事件 instated of enter
-
keyCode 38 是向上箭头。 “Enter”是keyCode 13。
-
@Karl-JohanSjögren 谢谢,已更新但仍未启动。
-
@Aid19801 您确定查询选择器返回正确的输入吗?你确定按下“回车”会有什么特别的作用吗?并且您不是在寻找“提交”表单?
标签: javascript