【发布时间】:2021-04-02 03:55:14
【问题描述】:
我有一个输入搜索框,可以搜索谷歌,它工作正常。我试图添加的是一个在按键输入时搜索的功能,我添加了该功能,但现在每次我单击输入搜索该功能时都会开始迭代并打开同一搜索的多个选项卡。如何将其限制为仅打开 1 个搜索选项卡?任何帮助表示赞赏。提前致谢。
function searchGoogle() {
document.getElementById("googleSearchButton").href =
(("https://www.google.com/search?q=") + (document.getElementById("googleSearchInput").value));
// Get the input field
var input = document.getElementById("googleSearchInput");
// 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("googleSearchButton").click();
}
});
}
.form-group {
width: 50%;
position: absolute;
top: 3%;
left: 4%;
z-index: 1;
}
.form-group img {
width: 6%;
height: auto;
position: absolute;
top: 50%;
right: 1%;
margin-right: 1%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
<div class="form-group ">
<input type="text" class="form-control" id="googleSearchInput" placeholder="Search The Web">
<a href="" id="googleSearchButton" onclick="searchGoogle()" target="_blank"> <img src="https://img.icons8.com/material-outlined/128/000000/search--v1.png" /></a>
</div>
【问题讨论】:
标签: javascript html