函数返回值' NaN'

时间:2015-10-28 15:35:38

标签: javascript

我正在编写一个代码来检查用户输入并根据它给出结果。但是这里的扭曲是字符串也可以包含单词“打”,这意味着十二个。看完下面的代码后,该东西将被清除:

HTML:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>iRock</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="css.css">
    </head>
    <body>
        <form>
            <label for="numDonut">Enter how many donuts you want:  </label>
            <input type="text" id="numDonut">
            <div id="totalDonuts"></div>
            <div id="submit" onclick="callDonut();">SUBMIT</div>
        </form>
        <script type="text/javascript" src="javascript.js"></script>
    </body>
</html>

JS:

//Get string number of donuts entered
var numDonutString = document.getElementById('numDonut').value;

function getTotalDonuts(donutString){
    var initialDonutCount = parseInt(donutString);
    var finalDonuts = 0;

    if(donutString.indexOf('dozen') != -1)
        finalDonuts = initialDonutCount * 12;
    else
        finalDonuts = initialDonutCount;

    return finalDonuts;
}
function callDonut(){
    document.getElementById('totalDonuts').textContent = getTotalDonuts(numDonutString);
}

现在问题在于:无论我给出什么输入,即使它没有包含“打打”这个词,该函数也会返回NaN,这是没有意义的。

可能是什么问题?

3 个答案:

答案 0 :(得分:3)

您遇到的问题是您已尝试预先定义var numDonutString = document.getElementById('numDonut').value;,但是这样做会获取值的副本,并且永远不会更新该值。

因此,您需要做的是每次单击SUBMIT按钮时获取新值。

jsFiddle:https://jsfiddle.net/CanvasCode/xue6sbz2/

function getTotalDonuts(donutString){
    alert(donutString);
    var initialDonutCount = parseInt(donutString);
    var finalDonuts = 0;

    if(donutString.indexOf('dozen') != -1)
        finalDonuts = initialDonutCount * 12;
    else
        finalDonuts = initialDonutCount;

    return finalDonuts;
}

function callDonut(){
    document.getElementById('totalDonuts').textContent = getTotalDonuts(document.getElementById('numDonut').value);
}

答案 1 :(得分:3)

您需要更改功能callDonut,如:

function callDonut(){
    document.getElementById('totalDonuts').textContent = getTotalDonuts(document.getElementById('numDonut').value);
}

问题:您没有将输入的新值重新分配给变量numDonutString

答案 2 :(得分:0)

问题出在callDonut函数中,您获得的文本框值仅在文档加载时,因此值始终为NaN

window.getTotalDonuts = function(donutString) {
  var initialDonutCount = parseInt(donutString);
  var finalDonuts = 0;
  if (donutString.indexOf('dozen') != -1) {
    finalDonuts = initialDonutCount * 12;
  } else {
    finalDonuts = initialDonutCount;
  }
  return finalDonuts || 0;
}

window.callDonut = function() {
  //Get string number of donuts entered
  var numDonutString = document.getElementById('numDonut').value;
  document.getElementById('totalDonuts').textContent = getTotalDonuts(numDonutString);
}
<form>
  <label for="numDonut">Enter how many donuts you want:</label>
  <input type="text" id="numDonut">
  <div id="totalDonuts"></div>
  <div id="submit" onclick="callDonut();">SUBMIT</div>
</form>
</body>

DEMO