2014-10-02 40 views
0

我无法将var mpg总数变成“Miles Per Gallon”文本字段。它与var $一起工作,但我试图摆脱快捷方式。我在Stackoverflow或Google上找不到答案。有人能够看到我出错的地方吗?MPG文本字段未使用Javascript进行更新getElementById

<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> 

回答

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字段将不会被更新。

0

你试图改变“省油”字段的值,但是你不告诉它你想要的值是多少:.value的()将只返回当前值,.value的( mpg)会尝试设置该值。你需要的东西,如:

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