繁体   English   中英

我怎样才能使它根据输入产生不同的结果?

[英]How can I make it so a different result occurs depending on an input?

我有以下代码,我想知道而不是这样做,以便如果输入数组中的任何变量,它将带您到index.php ,我想要它,所以如果输入第一个,它将带您到1.html ,如果输入 2,它将带您到2.html etc 这可能吗?

HTML 代码:

<center>
    <form
     name="myForm"
     onsubmit="return validateForm()"
     method="post"
    >
        <h1 style = "color:white;">Enter code </h1>
        <input type="text" name="value" style="padding: 5px; border-radius: 6px; border: 0px solid transparent;"/>
        <br><br>
        <input type="submit" class = "ex" value="Enter/submit" style="border-radius: 6px; font-size: 18px;display: inline-block; padding: 20px; border: none; background-color: royalblue; color: white;"/>
    </form>
</center>

JavaScript 代码:

var cars = ["Saab", "Volvo", "BMW"];
function validateForm() {
    var x = document.forms["myForm"]["value"].value;
    if (cars.indexOf(x) == -1) {
        alert("no car entered");
        return false;
    }

    var x = document.forms["myForm"]["value"].value;
    if (cars.indexOf(x) != -1) {
        window.location.href = "index.php";
        return false;
    }
}

像这样的东西? 只需将 console.log 替换为您想要的重定向即可。

 const cars = ["Saab", "Volvo", "BMW"] function validateForm() { const inputValue = document.forms["myForm"]["value"].value; if (inputValue === cars[0]) { console.log("Redirect to 1.html"); } else if (inputValue === cars[1]) { console.log("Redirect to 2.html"); } else if (inputValue === cars[2]) { console.log("Redirect to 3.html"); } else { console.log("no car entered") } return false; }
 <form name="myForm" onsubmit="return validateForm()" method="post"> Enter code <input id="formInput" type="text" name="value" /><br> <input type="submit" class="ex" value="Enter/submit" /> </form>

要重定向到 1.html、2.html 等形式的 URL 等,我们注意到所需的数字是汽车的索引。 所以我们要重定向到的地方就是这个 index.html

这是实现这一点的代码。

<center>
  <form name="myForm" onsubmit="return validateForm()" method="post">
    <h1 style = "color:black;">Enter code </h1><input type="text" name="value" style="padding: 5px; border-radius: 6px; border: 1px solid red;"/>
    <br><br><input type="submit" class = "ex" value="Enter/submit" style="border-radius: 6px; font-size: 18px;display: inline-block; padding: 20px; border: none; background-color: royalblue; color: white;"/>
  </form>
</center>
<script>
var cars = ["Saab", "Volvo", "BMW"];

function validateForm() {alert(document.forms);alert(document.forms["myForm"]["value"].value);
  var x = document.forms["myForm"]["value"].value;
  if(cars.indexOf(x) == -1){
    alert("no car entered");
    return false;
  }
  else{
    window.location.href = cars.indexOf(x) + ".html";
  }
}
</script>

笔记:

  • center 已弃用 - 改用 CSS
  • 问题中的代码两次声明 x
  • if...else 在上面使用,而不是两次测试条件
  • 由于正在重定向用户,因此最终的 return 语句似乎没有意义
  • 输入元素的边框设置为 0。对于这个测试,它被设置为 1px,颜色为红色,因此可以看到

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM