Javascript:输入值的双面转换

时间:2014-03-25 12:40:13

标签: javascript

我尝试使用两个<input type="numer">代码来转换彼此之间的货币。

HTML

<form method="post">
    <input type="number" id="credits" onkeydown="creditsToCash()" onkeypress="creditsToCash()" value="" placeholder="Credits"/>
    <input type="number" id="cash" onkeydown="cashToCredits()" onkeypress="cashToCredits()" value="" placeholder="Cash"/>
</form>

的JavaScript

var credits = document.getElementById('credits'),
cash = document.getElementById('cash');
function creditsToCash(){
    setTimeout(function() {
        crd = credits.value;
        crd2ch = crd / 2.5;
        cash.setAttribute('value', crd2ch);
    }, 10);
}
function cashToCredits(){
    setTimeout(function() {
        ch = cash.value;
        ch2crd = ch * 2.5;
        credits.setAttribute('value', ch2crd);
    }, 10);
}

如果我只在一侧键入一个数字,但是如果我尝试在另一个<input>上更改结果,那么整个脚本都会完全失败,直到刷新页面为止。

1 个答案:

答案 0 :(得分:0)

尝试清除未使用时的超时

var credits = document.getElementById('credits'),
cash = document.getElementById('cash');
var cashId = null;
var creditsId = null;
function creditsToCash(){
    if (cashId != null) clearTimeout(cashId);
    creditsId = setTimeout(function() {
        crd = credits.value;
        crd2ch = crd / 2.5;
        cash.setAttribute('value', crd2ch);
    }, 10);
}
function cashToCredits(){
    if (creditsId != null) clearTimeout(creditsId);
    cashId = setTimeout(function() {
        ch = cash.value;
        ch2crd = ch * 2.5;
        credits.setAttribute('value', ch2crd);
    }, 10);
}