[英]In java script how do I link these arrays with this user input so it will print out the food and the fruit
I am trying to get the user to put in a number press the submit button and then it outputs the food and the fruit together so that it will be like a lunch thing. 我试图让用户输入数字,然后按“提交”按钮,然后将食物和水果一起输出,这样就好像午餐一样。 PLease help. 请帮忙。 Thanks 谢谢
<!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>
You need to add an onchange handler to the input element or add a button with an onclick handler to trigger the action after the user enters a number. 您需要在输入元素上添加onchange处理程序,或者添加带有onclick处理程序的按钮以在用户输入数字后触发操作。 That should call a function to display the values, probably in another HTML element. 那应该调用一个函数来显示值,可能在另一个HTML元素中。 You can use addEventListener or simply add the call to the element something like this: 您可以使用addEventListener或将调用添加到元素中,如下所示:
<input type="number" name="x" min="0" max="5" onchange="showLunch(this);" /> // (note the closed input element!)
The onchange will fire when the user tabs out of the input field. 当用户跳出输入字段时,将触发onchange。 You may want to try a button with onclick or whatever. 您可能要尝试使用onclick或其他任何按钮。 Experiment. 实验。
Your form is not going to be posted to a server, so there's really no need for it. 您的表单不会被发布到服务器上,因此实际上不需要它。 Everything will happen in the Javascript code. 一切都会在Javascript代码中发生。 Your function could be something like: 您的功能可能类似于:
function showLunch( btn ) {
document.getElementById('lunch').innerHTML = "lunch is " + food(btn.value) + fruit[btn.value];
}
In the function I assume an added HTML div to hold the answer: 在函数中,我假设添加了HTML div以保存答案:
<div id="lunch" ></div>
This is just a start, you may need to clean it up as you go. 这只是一个开始,您可能需要在旅途中对其进行清理。 Have fun... 玩得开心...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.