javascript - 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>
解决方案
您永远不会更改选项的值,您只是在更新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>
推荐阅读
- c# - EF Core:AutoMapper ProjectTo ToListAsync 抛出“对象引用未设置为对象的实例”
- oracle - 如何在 oracle sql developer 中为 oracle e 业务套件表设置模式
- excel - 结合 IF、ISTEXT 和 LEN 函数
- python - 如何制作对数缩放的 Tkinter 滑块?
- google-cloud-platform - 无法将 dicom 文件从 GCP dicom 存储导出到具有原始文件名的存储
- google-apps-script - 当在特定列范围内输入特定单词/数字时,Google 应用程序脚本将提示用户
- c# - 带有 IDbDataParameter 参数的模拟方法
- python - 如何在银行网站上查找元素
- requirejs - 需要配置:未捕获的错误:脚本错误:datatables.net
- javascript - 使用与 Java 相同的 cryptojs 使用 Javascript 进行 AES 加密 - AES/CBC/PKCS5Padding