我正在尝试获取一个搜索框,当它接受输入时,它会将用户发送到特定页面。但出于某种原因,我无法弄清楚,在给出输入时它什么都不做。我的代码如下:
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script type="text/javascript">
var input = document.getElementById("search");
function sendToPage(){
if (input.value == "happy"){
location.href="suggestion_happy.html";
}
else if (input.value == "sad"){
location.href="suggestion_sad.html";
}
else {
alert('Invalid Input.');
}
}
</script>
</head>
<body>
<div>
<form onsubmit="sendToPage()">
<input type="text" method="put" id="search" placeholder="Search" value="">
</form>
</div>
</body>
</html>
请帮忙,我对 javascript 还是个新手 :)
最佳答案
你不需要创建一个表单来做到这一点
检查这段代码
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script type="text/javascript">
function sendToPage(){
var input = document.getElementById("search").value;
//alert(input);
if (input == "happy"){
location.href = "suggestion_happy.html";
return false;
}
else if (input == "sad"){
location.href = "suggestion_sad.html";
return false;
}
else {
alert('Invalid Input.');
}
}
</script>
</head>
<body>
<div>
<input type="text" method="put" id="search" placeholder="Search" value="">
<input type='submit' onclick="sendToPage();" />
</div>
</body>
</html>
关于javascript - 如何让搜索栏接受输入并转到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33329366/