简体   繁体   English

如何使用单选按钮从二维数组中获取多个输出?

[英]How do I get multiple outputs from a 2D array using radio buttons?

I am creating a webpage that allows users to search for a hiking trail based on difficulty.我正在创建一个网页,允许用户根据难度搜索远足径。 They will select either the 'Easy' or 'Hard' radio button and will be provided with a corresponding trail.他们将 select 选择“简单”或“困难”单选按钮,并将提供相应的线索。

Here is my HTML:这是我的 HTML:

Hiking NL! 远足荷兰!
 <meta content="width=device-width, initial-scale=1" name="viewport" /> <link rel="stylesheet" type="text/css" href="style.css">
<script src="src/index.js"></script>

 <script src="src/index.js"></script>

I have stored the trail names, along with the difficulty and length in a 2D array.我已经将路径名称以及难度和长度存储在一个二维数组中。 I have been able to make it so one trail name will appear with each radio button, but when I add another 'Easy' trail to the array, only one name will show up.我已经能够做到这一点,因此每个单选按钮都会显示一个路径名称,但是当我将另一条“简单”路径添加到数组时,只会显示一个名称。 It looks like it is skipping over the first row of the array.看起来它正在跳过数组的第一行。 How do I get it to output multiple trail names?我如何获得 output 多个路径名称?

This is my script:这是我的脚本:

 //Allows console.log to display what radio button was selected. let chosen; document.getElementById('easy').onclick = function () { console.log("Easy") chosen = "Easy"; } document.getElementById('hard').onclick = function () { console.log("Hard") chosen = "Hard"; } function displayArray() { //Two dimensional array let hikes = [ ['Easy','Silver Mine Head Path', 5], ['Hard','White Horse Path', 4], ['Easy','Father Troy', 3] ]; console.log(hikes) let results = []; console.log(results); for(i = 0; i < hikes.length; i++) { if(hikes[i][0] == chosen){ //Checks row for difficulty console.log("Row: "+chosen) results[i] = hikes[i][1]; //Shows corresponding hike with chosen difficulty document.getElementById("output").innerHTML //Shows users their result = "Trail: "+results[i]; } } }

Try replacing your for loop with this:尝试用这个替换你的 for 循环:

for (i = 0; i < hikes.length; i++) {
  if (hikes[i][0] == chosen) {
    //Checks row for difficulty
    console.log("Row: " + chosen);

    results.push(hikes[i][1]); //Shows corresponding hike with chosen difficulty
  }
}

document.getElementById("output").innerHTML = "Trail(s): " + results.join(", "); //Shows users their result

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

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