簡體   English   中英

在Java腳本中,如何將這些數組與該用戶輸入鏈接起來,以便將食物和水果打印出來

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

我試圖讓用戶輸入數字,然后按“提交”按鈕,然后將食物和水果一起輸出,這樣就好像午餐一樣。 請幫忙。 謝謝

<!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>

您需要在輸入元素上添加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];
}

在函數中,我假設添加了HTML div以保存答案:

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

這只是一個開始,您可能需要在旅途中對其進行清理。 玩得開心...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM