如何使Enter键按下搜索按钮?预先感谢。
function search(query) {
if (query.slice(0, 7) == "http://") {
// window.location.href = query
window.open(query, '_blank');
} else {
// window.location.href = "https://www.google.com/search?q=" + query
debugger;
window.open("https://www.google.com/search?q=" + query, '_blank');
}
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="box">
<div class="container-1">
<input type="search" id="search" placeholder="Search..." />
<div class="icon" onclick="search(document.getElementById('search').value)"><i class="fa fa-search"></i></div>
</div>
</div>
答案 0 :(得分:0)
这里是一个例子:
// Get the input field
var input = document.getElementById("myInput");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});
那应该回答你的问题。
答案 1 :(得分:0)
实际上,只需使用表单并按名称检索输入即可。
请注意,我们甚至可以删除按钮<input type="submit">
,我们仍然可以使用 ENTER 键。
我留下了最简单的逻辑:
function search(query){
query.preventDefault();
let vquery = query.target.elements["search"].value;
console.log(vquery)
}
something.addEventListener("submit", search, false)
<div class="box">
<div class="container-1">
<form id="something">
<input name="search" placeholder="Search... type ENTER to submit or use the button -->">
<input type="submit">
</form>
<div class="icon" ></div>
</div>
</div>