带有 html 选择列表的 Javascript 数组

标签 javascript

<分区>

我有一个从 0 到 4 的选择列表,当选择一个数字时,它将输出数组中的名称。而不是在选择数字 1 并获得输出“Adam”时,我只为每个数字得到“Ron”。

friends = new Array('Alex', 'Adam', 'Jake', 'Cydney', 'Ron');

document.getElementById('go').onclick = function() {

  var nameSelected = document.getElementById('index').value;

  oneArrayValue = friends[0];

  oneArrayValue = friends[1];

  oneArrayValue = friends[2];

  oneArrayValue = friends[3];

  oneArrayValue = friends[4];

  document.getElementById('result').value = nameSelected;

};
<body>
  <select id='number' name=''>
            <option value = '0'>0</option>
            <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>
  <button id='go' class=''>GO</button>
  <input id='result' name='' value='' class=''>
  <script src='js/javascript 07.js'></script>
</body>

最佳答案

friends = new Array('Alex','Adam','Jake','Cydney','Ron');
/*
    you can even declare using the following:  
  
    friends = ['Alex','Adam','Jake','Cydney','Ron']; // <- this
*/

document.getElementById('go').onclick = function () {
    var nameSelected = document.getElementById('number').value;

    // getting the name from the index selected
    oneArrayValue = friends[nameSelected];
    document.getElementById('result').value = oneArrayValue;
};
    <select id = 'number' name = ''>

        <option value = '0'>0</option>
        <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>
    <button id = 'go' class = ''>GO</button>
    <input id = 'result' name = '' value = '' class = ''>

关于带有 html 选择列表的 Javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46855580/

相关文章:

javascript - 从脚本/命令行执行浏览器页面/javascript

javascript - 如何修复错误窗口未定义

javascript - iFrame 嵌套在具有相同 ID 的 iFrame 中

javascript - 使用功能设置两个以上 Highchart Solid Gauge 的最小值和最大值

javascript - 如何在网站加载时显示一次 Javascript 提示?

javascript - 来自使用 jQuery insideHTML 的页面的 PHP file_get_contents

javascript - 如何将现有回调 API 转换为 Promise?

JavaScript this 指的是窗口而不是函数内部的对象

javascript - 为什么 JQuery 在尝试从输入类型文本中捕获值时返回 Undefined?

javascript - 为什么这些 twix 范围测试会失败?