javascript - Javascript 在加载页面进行搜索输入时触发 Enter 键而无需实际按下 Enter 键
问题描述
我正在创建一个包含搜索输入的加载页面,该值是从 url 生成的
http://localhost/example?i%search%this
在 onload 页面中,我创建了这个 =
<body onload="myFunction()">
// this is where i put the input search that needs Enter to active search
<input type="text" class="form-control searchable-input floatL value-not-empty" placeholder="Search Badan Usaha" name="s545858fe" id="s545858fe">
</body>
<script>
function myFunction() {
var newURL = window.location.search.substr(1);
var uri_dec = decodeURIComponent(newURL);
document.getElementById("s545858fe").value = uri_dec;
}
</script>
我的实际结果是我在输入搜索中得到“我搜索这个”文本,但它不执行搜索,因为搜索需要输入键才能执行
解决方案
<input>
您可以通过创建一个KeyboardEvent()
然后调度事件来触发内部的 Enter 按键:
const entry = document.getElementById('s545858fe');
entry.addEventListener('keypress', function (event) {
console.log('Keypress in entry with value: ' + this.value);
}, false);
function myFunction() {
const evt = new KeyboardEvent('keypress', {});
entry.focus();
entry.value = "new value";
entry.dispatchEvent(evt);
}
<body onload="myFunction()">
<input type="text" class="form-control searchable-input floatL value-not-empty" placeholder="Search Badan Usaha" name="s545858fe" id="s545858fe">
</body>
推荐阅读
- python - 是否可以基于某些列查找从 CSV 文件中读取数据,而无需将整个文件读入内存?
- flutter - NotifyListeners() 在 Flutter 中不能正常工作
- javascript - 使用制表符创建页面持久性
- c# - Release模式下的程序集反射问题
- java - java中的Haskell,我如何在java中实现“any”(haskell)?
- cypress - 赛普拉斯断言等于和大于
- mysql - 如何在 MySQL 中连接此脚本中的列?
- php - 具有动态 url 段的 nginx php-fpm 未被 php-fpm 解析
- perl - Perl tar 文件递归创建目录
- sql-server - SQL 嵌套连接问题