在java脚本中,我如何将这些数组与这个用户输入链接起来,以便它将打印出食物和水果

In java script how do I link these arrays with this user input so it will print out the food and the fruit

本文关键字:打印 起来 链接 脚本 java 用户 数组 输入      更新时间:2023-09-26

我试图让用户输入一个数字,按提交按钮,然后它输出食物和水果在一起,这样它就像一个午餐的事情。请帮助。由于

<!DOCTYPE html>
<html>
<body>
<form action="demo_form.asp">
  Type of food (between 0 and 5): <input type="number" name="x" min="0" max="5">
  </form>
<script>
var food = new Array();
food[0] = "hot dog";
food[1] = "chicken fingers";
food[2] = "veggie sandwhich";
food[3] = "Home fries"
food[4] = "pb and j"
food[5] = "pizza"
var y = Math.floor(Math.random()*6)
var fruit = new Array();
fruit[0] = "orange";
fruit[1] = "banana";
fruit[2] = "apple";
fruit[3] = "kiwi"
fruit[4] = "lemon"
fruit[5] = "peach"
{
document.write(food[x] + fruit[y]+"<br>");
}
</script>

</body>
</html>

您需要为input元素添加一个onchange处理程序,或者添加一个带有onclick处理程序的按钮,以便在用户输入数字后触发操作。它应该调用一个函数来显示值,可能在另一个HTML元素中。您可以使用addEventListener或简单地将调用添加到元素中,如下所示:

<input type="number" name="x" min="0" max="5" onchange="showLunch(this);" />  // (note the closed input element!)

onchange将在用户退出输入字段时触发。你可以试试onclick之类的按钮。实验。

你的表单不会被发送到服务器,所以真的没有必要。一切都将在Javascript代码中发生。函数可以是这样的:

function showLunch( btn ) {
   document.getElementById('lunch').innerHTML = "lunch is " + food(btn.value) + fruit[btn.value];
}

在函数中,我假设添加了一个HTMLdiv来保存答案:

<div id="lunch" ></div>

这只是一个开始,你可能需要在你的过程中清理它。玩得开心…