首页 > 解决方案 > 下拉列表和数组名称连接

问题描述

我创建了 3 个具有 3 个唯一名称的数组,每个数组都预加载了 5 个不同的数字。我还创建了一个下拉列表,其中包含 3 个数组名称。我创建的第二个下拉列表包括“1,2,3,4,5”作为数组索引。

用户从第一个下拉列表中选择阵列名称,并从第二个下拉列表中选择一个数字。我希望根据用户选择的数组名称和索引号显示该值。有人可以帮忙吗?

标签: javascriptarrays

解决方案


// assign array
const a = [2, 3, 5, 1, 2];
const b = [8, 4, 7, 6, 3];
const c = [9, 2, 8, 5, 1];

// get the value from dropdown list (html)
function myFunction() {
  const e = document.getElementById("myArray").value;
  const f = document.getElementById("myIndex").value;
  const d = parseInt(f); //convert it from string to int

  //use if statement to choose the correct array
  if (e == "a") {
    return (document.getElementById("p1").innerHTML = a[d - 1]);
  }

  if (e == "b") {
    return (document.getElementById("p1").innerHTML = b[d - 1]);
  }

  if (e == "c") {
    return (document.getElementById("p1").innerHTML = c[d - 1]);
  }
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Array</title>
  </head>
  <body>
    <p>Select your Array:</p>
    <select id="myArray">
      <option value="a">a</option>
      <option value="b">b</option>
      <option value="c">c</option>
    </select>

    <p>Select your index:</p>
    <select id="myIndex">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
    </select>
    <br />
    <br />

    <button type="button" onclick="myFunction()">Submit</button>

    <p id="p1"></p>
   
  </body>
</html>


推荐阅读