在将字符串转换为int时添加总值时遇到问题

问题描述:

我有两个选择字段向用户提出两个不同的问题,并根据所选值将总值添加到最终总计。我并不完全理解为什么最终总计说我的$ NaN美元时,我先选择第二个选择字段,但如果我先选择第一个选择字段,那么它不显示$ NaN USD。在将字符串转换为int时添加总值时遇到问题

var total; 
 

 
$('.form-contro').on('change', function() { 
 
    var get = $('#form-contro option:selected').val(); 
 
    total = Number(get); 
 

 
    $('.text-center h2 span').html(total + " USD"); 
 
}); 
 

 

 
$('.form-contr').on('change', function() { 
 
    var get = $('#form-contr option:selected').val(); 
 

 
    if (get === 'no') { 
 
    total = 1000; 
 
    } else if (get === 'yes') { 
 
    total = total + 30; 
 
    } 
 

 
    $('.text-center h2 span').html(total + " USD"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label class="wrapper" style="margin-top: 20px; font-size: 12px; color: #888; font-family: 'Raleway', sans-serif;" for="states">Number of items:</label> 
 
<select class="form-contro" id="form-contro" style="width: 320px; height: 40px; text-indent: 10px; display: block; margin: 0 auto; border-radius: 4px; border-style: solid; border-color: #343434;"> 
 
    <option value="90" id="items">1 Item</option> 
 
    <option value="95.50" id="items">2 Items</option> 
 
    <option value="100" id="items">3 Items</option> 
 
    <option value="105" id="items">4 Item</option> 
 
</select> 
 

 
<label class="wrapper" style="margin-top: 20px; font-size: 12px; color: #888; font-family: 'Raleway', sans-serif;" for="states">Will you be flying?</label> 
 
<select class="form-contr" id="form-contr" style="width: 320px; height: 40px; text-indent: 10px; display: block; margin: 0 auto; border-radius: 4px; border-style: solid; border-color: #343434;"> 
 
    <option value="no" id="items">No</option> 
 
    <option value="yes" id="items">Yes</option> 
 
</select> 
 

 
<div class="text-center" style="clear: both;"> 
 
    <h2 style="margin-top: 40px;">Total amount $<span id="new_text">90 USD</span></h2> 
 
</div>

我是相当新的JavaScript所以任何帮助表示赞赏,因为我一直在这个问题上一段时间。

+0

我的最终目标是将两个选择值一起添加而没有获得$ NaN。 – mur7ay

你没有给总的初始值,所以在顶部,使总价值: var total = 0;

你没有得到楠倒过来的原因,是因为你使用Number(get),如果为null,则它将默认值为0。

+0

哇,那真是超级简单..谢谢! – mur7ay