gpt4 book ai didi

javascript - 如何计算来自不同选择的选项的值

转载 作者:行者123 更新时间:2023-11-30 15:32:59 25 4
gpt4 key购买 nike

我正在尝试计算选定索引的值。下拉菜单是动态的,所以我可能有 3 个下拉菜单、5 个下拉菜单或 8 个下拉菜单。当我尝试计算所选索引的值时,我得到了 NaN。我错过了什么吗?

function calculate() {
var calculationSpan = document.getElementById("calculationSpan");
var add;
var selects = document.querySelectorAll(".rooms");
selects.forEach(function (select) {
var roomsOfType = select.options[select.selectedIndex].value;
if (roomsOfType != 0) {
add = parseInt(add) + parseInt(select.options[select.selectedIndex].value);
}
});
calculationSpan.innerHTML = add;
}
<select class="rooms">
<option value="0">0</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>


<select class="rooms">
<option value="0">0</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
</select>

<select class="rooms">
<option value="0">0</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>

<button onclick="calculate()">
Calculate
</button>
<span id="calculationSpan"></span>

最佳答案

基本上,您需要为 add 设置起始值。

var add = 0;

而且你还得借Array#forEach ,因为 selects 是一个类似对象的数组,但不是数组。

你需要Function#callselects 用作 thisArg

[].forEach.call(selects, function (/* ... */ ))

function calculate() {
var calculationSpan = document.getElementById("calculationSpan"),
add = 0,
selects = document.querySelectorAll(".rooms");

[].forEach.call(selects, function (select) {
var roomsOfType = +select.options[select.selectedIndex].value;
if (roomsOfType) {
add += roomsOfType;
}
});
calculationSpan.innerHTML = add;
}
<select class="rooms"><option value="0">0</option><option value="1">One</option><option value="2">Two</option><option value="3">Three</option></select>
<select class="rooms"><option value="0">0</option><option value="1">One</option><option value="2">Two</option><option value="3">Three</option><option value="4">Four</option><option value="5">Five</option><option value="6">Six</option></select>
<select class="rooms"><option value="0">0</option><option value="1">One</option><option value="2">Two</option><option value="3">Three</option><option value="4">Four</option></select>
<button onclick="calculate()">Calculate</button>
<span id="calculationSpan"></span>

关于javascript - 如何计算来自不同选择的选项的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41981655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com