2017-06-14 58 views
2

我在解决如何将JavaScript功能应用于HTML时遇到问题。我认为这很简单,但由于某种原因,我的代码不起作用。如何将JavaScript函数应用于选择表单?

下面是代码的HTML部分。它包括一个输入,两个下拉菜单(用于选择不同的货币类型),一个按钮和一个输出答案的部分。我已经删除了大部分代码,以便更易于阅读,并且因为它们基本上都是重复的。

<input type="number" id="money" placeholder="Enter starting cash" /> 
<select id="incur"> 
     <option value = "1">USD</option> 
</select> 
<select id="outcur"> 
     <option value = "2">CAD</option> 
</select> 
<button type="submit" id="start">Submit</button> 
<p id="result" style="font-size:20pt; color:#E00;"></p> 

的HTML出现在页面上很好,但它没有任何功能。点击提交不做任何事情,我从来没有看到结果段落标记。

下面是JavaScript的一部分。其余部分同样也是几乎相同的东西,但是被复制和粘贴并且具有修改后的值。

这里是输入部分:

document.getElementById("start").onclick = function() { 
     'use strict'; 

     var incur = document.getElementById("incur"); 
     incur = incur.options[incur.selectedIndex].value; 

     var outcur = document.getElementById("outcur"); 
     outcur = outcur.options[outcur.selectedIndex].value; 

     var m = document.getElementById("money").value; 


     /* USD */ 
     if (incur == 1) { 
      var i = "USD"; 
      if (outcur == 2){ 
       report(m, i, (m * 1.35).toFixed(2), "CAD"); 
      } 
     } 
    }; 

下面是输出部分:

var report = function (inmoney, intype, outmoney, outtype) { 
     'use strict'; 
     document.getElementById("result").innerHTML = 
      inmoney + " " + intype + " = " + outmoney + " " + outtype; 
    }; 

为什么我的代码没有做任何事情?我似乎无法找出什么毛病,除非我不知道如何使用的document.getElementById

的代码应该像这样的:在输入表单

  1. 输入一个数值,说10
  2. 输入和输出(这里的唯一选项是美元和CAD)
  3. 按选择一个值“提交”
  4. 的JavaScript计算,10美元= 13.23 CAD并输出。

回答

1

你需要它的使用之前,你report函数变量的声明移到:

document.getElementById("start").onclick = function() { 
 
    'use strict'; 
 

 
    var incur = document.getElementById("incur"); 
 
    incur = incur.options[incur.selectedIndex].value; 
 

 
    var outcur = document.getElementById("outcur"); 
 
    outcur = outcur.options[outcur.selectedIndex].value; 
 

 
    var m = document.getElementById("money").value; 
 

 
    var report = function(inmoney, intype, outmoney, outtype) { 
 
    'use strict'; 
 
    document.getElementById("result").innerHTML = 
 
     inmoney + " " + intype + " = " + outmoney + " " + outtype; 
 
    }; 
 

 
    /* USD */ 
 
    if (incur == 1) { 
 
    var i = "USD"; 
 
    if (outcur == 2) { 
 
     report(m, i, (m * 1.35).toFixed(2), "CAD"); 
 
    } 
 
    } 
 
}
<input type="number" id="money" placeholder="Enter starting cash" /> 
 
<select id="incur"> 
 
     <option value = "1">USD</option> 
 
</select> 
 
<select id="outcur"> 
 
     <option value = "2">CAD</option> 
 
</select> 
 
<button type="submit" id="start">Submit</button> 
 
<p id="result" style="font-size:20pt; color:#E00;"></p>

看看function declaration hoisting的根本原因。

+0

这并没有工作 – Taylor

+0

我在我的答案中提供了一个可执行代码段,可以证明这是可行的。如果它不适合你,那么你的问题中没有提供一些代码中的问题。 –

相关问题