我的功能不起作用

问题描述 投票:0回答:2

点击搜索按钮后,该功能可以将搜索输入附加到Google URL。然而,似乎该函数忽略了该变量,因为它重定向到Google的主页,尽管在搜索栏中输入了某些内容。

document.getElementById('searchbtn').onclick = searchExplore;
function searchExplore () {
 var input = document.getElementById('searchbar').value;   
 document.getElementById('searchform').action = 'http://www.google.com/search?q='+input;
}
body{
}
.search{
  text-align:center;
  background: url("http://dash.ga.co/assets/anna-bg.png");
  background-size:cover;
  background-position: center;
  padding:20px;
  }
form{
  display:inline-flex;
}
#searchbar{
  font-size:35px;
  border: 0;
  padding: 0px 0 0 20px;
  border-radius:20px 0 0 20px;
  outline: 0;
  font-family: 'Bitter', serif;
  }
#searchbtn{
  font-size:35px;
  border: 0;
  padding: 10px;
  border-radius: 0 20px 20px 0;
  outline: 0;
  width: 90px; 
  cursor: pointer;
}

#searchbar:hover,#searchbar:focus{
  box-shadow:-3px 3px 15px;
}
#searchbtn:hover,#searchbtn:focus{
  box-shadow:-.1px 3px 15px 1px;
}
<!DOCTYPE html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Bitter" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
  <link rel="stylesheet" href="mypen1.css" type="text/css"/>
  <title>MJ Search</title>
  
</head>
<body>
  <div class="search">
    <form id="searchform" action="">
         <input id="searchbar" type= "search" placeholder="Search & Explore..."/>
         <button id="searchbtn"><i class="fa fa-search"></i></button>
    </form>
  </div>
  <script type="text/javascript" src="mypen1.js"></script> 
</body>    
javascript html css
2个回答
0
投票

HTML文件:

<form id="searchform" action="" method="get" onsubmit="return searchExplore()">
     <input id="searchbar" type= "search" placeholder="Search & Explore..."/>
     <input type="submit" />
</form>

JS档案:

function searchExplore () {
    var input = document.getElementById('searchbar').value;
    window.location = 'http://www.google.com/search?q='+input;
    return false;
}

希望这可以帮助


0
投票

如果你必须使用表单,那么你需要调用event.preventDefault()作为函数中的第一个语句,(还需要将函数定义修改为 - > searchExplore(event))

否则,从html中删除表单,只需在searchExplore函数中使用document.location = 'http://www.google.com/search?q='+input;,你也不需要使用event.preventDefault()

© www.soinside.com 2019 - 2024. All rights reserved.