我正在尝试遍历一个选择表单,以便在单击时增加所选选项的值。我做了一些搜索,但没有找到我需要的东西。这是 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>
最佳答案
您永远不会更改选项的值,您只是在更新 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>
关于JavaScript循环选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50978907/