首页 > 解决方案 > JavaScript 循环选择选项

问题描述

我正在尝试遍历选择表单以在单击时增加所选选项的值。我已经进行了一些搜索,但没有找到我需要的东西..这是 html

var counter = 0;
function myFn(){
  var myOptionIndex = document.getElementById('selectForm').selectedIndex;
  var myOptionValue = document.getElementById('selectForm').value;
  var myOption = document.getElementById('selectForm').options;

  for (var i = 0; i < myOption[myOptionValue].value; i++) {
    counter++;
  }

  document.getElementById('results').innerHTML = myOption[myOptionIndex].text 
  + " has been selected " + counter + " times";
}
<form action="" id="voteForm">
    <select name="select-form" id="selectForm">
        <option value="1"> Option 1</option>
        <option value="1"> Option 2</option>
    </select>
    <button type="button" id="castVote" onclick="myFn();">Cast Your 
    Vote
   </button>        
</form>
<div id="results"></div>

标签: javascripthtmlformsloopsincrement

解决方案


您永远不会更改选项的值,您只是在更新counter变量。该变量没有关于每个选项的信息。

不需要循环,只需使用选定的索引。

并且您应该将选项的初始值设置为0,因为它们都没有收到任何投票。

var counter = 0;
function myFn(){
  var myOption = document.getElementById('selectForm').options;
  var myOptionIndex = document.getElementById('selectForm').selectedIndex;
  var myOptionValue = myOption[myOptionIndex].value;
  myOptionValue++;
  myOption[myOptionIndex].value = myOptionValue;

  document.getElementById('results').innerHTML = myOption[myOptionIndex].text 
  + " has been selected " + myOptionValue + " times";
}
<form action="" id="voteForm">
    <select name="select-form" id="selectForm">
        <option value="0"> Option 1</option>
        <option value="0"> Option 2</option>
    </select>
    <button type="button" id="castVote" onclick="myFn();">Cast Your 
    Vote
   </button>        
</form>
<div id="results"></div>


推荐阅读