MPG文本字段未使用Javascript getElementById进行更新

时间:2014-10-02 16:33:37

标签: javascript textbox textfield

我无法将var mpg total添加到“Miles Per Gallon”文本字段中。它与var $一起工作,但我试图摆脱快捷方式。我没有在Stackoverflow或Google上找到答案。有人能看到我哪里出错吗?

<script>
    var $ = function (id) {
        return document.getElementById(id);
    }                           

    var calculateMpg = function () {            
        var miles = parseFloat($("miles").value); 
          var gallons = parseFloat($("gallons").value); 

        if (isNaN(miles) || isNaN(gallons)) {    
            alert("Both entries must be numeric"); 
        }
        else {                      
            var mpg = miles / gallons;       
            function (id) {
                return (document.getElementById("mpg").value).toFixed(3); 
            }
        }
    }
    window.onload = function () {       
        $("calculate").onclick = calculateMpg;  
        $("gallons").focus();         
    }
</script>

</head>

<body>
<section>
    <h1>Calculate Miles Per Gallon</h1>
    <label for="miles">Miles Driven:</label>
    <input type="text" id="miles"><br>

    <label for="gallons">Gallons of Gas Used:</label>
    <input type="text" id="gallons"><br>

    <label for="mpg">Miles Per Gallon</label>
    <input type="text" id="mpg" disabled><br>

    <label>&nbsp;</label>
    <input type="button" id="calculate" value="Calculate MPG"><br>
</section>

2 个答案:

答案 0 :(得分:1)

只需获取上述代码即可在文本字段中显示mpg:

<script>
    var $ = function (id) {
        return document.getElementById(id);
    }                           

    var calculateMpg = function () {            
        var miles = parseFloat($("miles").value); 
          var gallons = parseFloat($("gallons").value); 

        if (isNaN(miles) || isNaN(gallons)) {    
            alert("Both entries must be numeric"); 
        }
        else {                      
            var mpg = miles / gallons;       
            document.getElementById("mpg").value = mpg.toFixed(3);
            //function (id) {
            //    return (document.getElementById("mpg").value).toFixed(3); 
            //}
        }
    }
    window.onload = function () {       
        $("calculate").onclick = calculateMpg;  
        $("gallons").focus();         
    }
</script>

在注释掉的代码中:无法定义像这样的匿名函数。即使有可能,也不会在任何地方调用该函数,因此不会更新mpg字段。

答案 1 :(得分:0)

您正在尝试更改“mpg”的价值。字段,但你没有告诉它你想要的值是什么:.value()只返回当前值,.value(mpg)将尝试设置值。你需要这样的东西:

var set_mpg_field = function(mpg){
  var mpg_field = document.getElementById("mpg");
  mpg_field.value(mpg.toFixed(3));
}