parseInt没有得到额外的回报

时间:2013-12-13 00:31:46

标签: javascript function parseint

var select;
window.onload = function () {
var select = document.getElementById("money");
console.log(select);
}

function changedepositedInput(objDropDown) {
console.log(parseInt(objDropDown));
var objdeposited = document.getElementById("deposited");
objdeposited.value=parseInt(objdeposited.value);
var total=parseInt(objdeposited.value);
objdeposited.value = parseInt(objDropDown.value+total);
objdeposited.value = parseInt(objdeposited.value);
}
</script>
<h1>Vending Machine Project</h1>
<form name="vendingmachine" action=" ">
Choose Bevrage<br>
        <input name="item" type="radio" value="water" checked="checked">Water 75 cents<br>
        <input name="item" type="radio" value="soda">Soda $1.50<br>
        <input name="item" type="radio" value="coffee">Coffee $1.00<br>
        <input name="item" type="radio" value="beer">Beer $2.00<br>
<p>
    <label>Deposit Money:
        <select name="money" id="money" onchange="changedepositedInput(this)">
            <option>Choose Amount</option>
            <option value="10">10 cents</option>
            <option value="25">25 cents</option>
            <option value="50">50 cents</option>
            <option value="75">75 cents</option>
            <option value="100">$1.00</option>
        </select>
    </label>
</p>
<p>Total Deposited:<input name="deposited" id="deposited" type="text" readonly="TRUE" value=" "></p>

使用此代码我没有得到一个实数的返回,例如在下拉菜单中我会选择两个值,即50和75,它们将组合为5075,这是否意味着它仍然运行它作为字符串在哪里,如果是这样的话?

1 个答案:

答案 0 :(得分:1)

  

例如在下拉菜单中我会选择两个值,即50和75,它们将合并为5075,这是否意味着它仍然在某处运行它作为字符串,如果是这样的话?

是的,在这里:

objdeposited.value = parseInt(objDropDown.value+total);

objDropDown.value是一个字符串,例如'50'total是一个数字,例如75

在JavaScript中,'50'+75'5075'

您可以替换这3行

var total=parseInt(objdeposited.value);
objdeposited.value = parseInt(objDropDown.value+total);
objdeposited.value = parseInt(objdeposited.value);

var total = parseInt(objdeposited.value);
objdeposited.value = parseInt(objDropDown.value||'0') + total;

编辑:

deposited值的默认值是空格" ",这导致了问题。将其更改为空字符串""。还要对所有对parseInt(或parseFloat)的调用添加||'0'。请参阅http://jsfiddle.net/es2yS/1/