首页 > 解决方案 > 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>

我的实际结果是我在输入搜索中得到“我搜索这个”文本,但它不执行搜索,因为搜索需要输入键才能执行

标签: javascriptphphtml

解决方案


<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>


推荐阅读