我尝试遍历一个select表单,以便在单击时增加所选选项的值。我做了一些搜索,但没有找到什么--I need..Here is the 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>
发布于 2018-06-22 10:24:28
你实际上不需要任何计数器。您可以使用myOptionValue
变量,因为它等于所选选项的实际值。此外,for
循环也是不必要的。您已经有了变量myOptionIndex
,它等于所选option
的索引。现在您只需要在函数中增加myOptionValue
的值,并在results
- div
中显示此变量而不是counter
。它看起来像这样:
function myFn(){
var myOptionIndex = document.getElementById('selectForm').selectedIndex;
var myOptionValue = document.getElementById('selectForm').options[myOptionIndex].value;
var myOption = document.getElementById('selectForm').options;
myOptionValue++;
document.getElementById('selectForm').options[myOptionIndex].value++;
document.getElementById('results').innerHTML = myOption[myOptionIndex].text
+ " has been selected " + myOptionValue + " times";
}
Here还演示了此示例的jsfiddle。
发布于 2018-06-22 08:37:50
您永远不会更改选项的值,您只需要更新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>
发布于 2018-06-22 08:25:43
我为我的英语道歉。切中要害-只有当表单发生更改时,脚本才会起作用。也就是说,如果选择了第一个选项,然后再次选择它-计数器将不会增加。
let increase=()=>results.innerText=`${selectForm.options[selectForm.selectedIndex].innerText} has been selected ${selectForm.options[selectForm.selectedIndex].value++} times`;
voteForm.addEventListener('change',increase);
<form id="voteForm" action="">
<select id="selectForm" name="select-form">
<option value="1"> Option 1</option>
<option value="1"> Option 2</option>
</select>
<button id="castVote" type="button">
Cast Your
Vote
</button>
</form>
<div id="results"></div>
https://stackoverflow.com/questions/50978907
复制相似问题