Javascript 选择选项在值之前始终显示 '0'

标签 javascript parseint

我在获取选择选项的值并计算它时遇到问题,问题是每次我选择一个选项时,它前面都会显示一个随机的“0”。任何帮助将不胜感激,这是相关代码:

               <div class="otherCars">  
                    <label for="otherCars">Do you drive any other cars?</label> 
                    <select name="otherCars" class="style1" id="carsSelect"  onchange="getQuote()" onblur="validateSelect('cars')" >
                        <option value="empty">-Please select-</option>
                        <option value="10" id="car1">No access to any other cars </option>
                        <option value="20">Own another car</option>
                        <option value="100">Named driver on another policy</option>
                        <option value="100">Company car (including personal use)</option>
                        <option value="100">Company car (excluding personal use)</option>
                    </select>
                </div><!-- Closing div tag-->

Javascript:

function getQuote(){
var disqualifiedDifference = 0;
var genderDifference = 0;
var carDifference = 0;
var menuSelect = document.getElementById("carsSelect");
var carValue = menuSelect.options[menuSelect.selectedIndex].value;

function genderPrice(){
    if (document.getElementById("male").checked){
        genderDifference += 200;
        }
    if (document.getElementById("female").checked){
        genderDifference += 175;
        }
        } 

function disqoPrice(){
    if (document.getElementById("yes").checked){
        disqualifiedDifference += 300;
        }
    if (document.getElementById("no").checked){
        disqualifiedDifference += 0;
        }
        } 

function carPrice(){
    if (document.getElementById("car1").selected){
        carDifference += 200;
        }
    if (document.getElementById("car2").selected){
        carDifference += 20;
        }
        }



genderPrice();
disqoPrice();

    var totalPrice = disqualifiedDifference + genderDifference + carDifference + carValue;
    document.getElementById('totalPrice').innerHTML = totalPrice;
} //end of CalculateTotal

最佳答案

menuSelect.options[menuSelect.selectedIndex].value 返回一个字符串,这意味着 + 运算符将执行字符串连接而不是加法。在尝试进行算术运算之前,将值转换为 Number

var carValue = +menuSelect.options[menuSelect.selectedIndex].value;
//             ^ unary + operator casts a string to a number

关于Javascript 选择选项在值之前始终显示 '0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26662347/

相关文章:

javascript - 映射到发送 props ReactJs

javascript - 从按钮列表创建可重复使用的按钮 css/jquery

javascript - NaN 等于 NaN 吗?

java - 数据未通过 jtable 保存在数据库中(已编辑)

java - 为什么这个 Java parseInt 十六进制字符串会导致 NumberFormatException?

javascript - firebase简单登录教程缺少用户

javascript - 如何从 Web 应用程序生成访问 token 并嵌入 token

java - 此代码为 Integer.parseInt(data[2]) 行抛出异常

Javascript 嵌套异常处理