如何从不同的选择中计算期权的价值

时间:2017-02-01 14:00:15

标签: javascript

我正在尝试计算所选索引的值。下拉动态是动态的,所以我可能有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>

1 个答案:

答案 0 :(得分:2)

基本上你需要add的起始值。

var add = 0;

你必须借用Array#forEach,因为selects是一个类似于对象的数组,但不是数组。

您需要Function#call才能将selects用作thisArg

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

&#13;
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;