将美元兑换成其他货币

时间:2016-12-09 18:07:21

标签: javascript html

我是一个完整的菜鸟,并试图学习,我想尝试将美元兑换成其他货币。已经工作了几个小时,并不完全确定如何进行;试图得到:

可以输入美元金额的方框,  下拉选择货币,  输出功能显示转换量。

<!DOCTYPE html>
<head>
<script language="JavaScript">

function usdfunc(){
document.converter.eur.value = document.converter.dollar.value * 0.73640
document.converter.gbp.value = document.converter.dollar.value * 0.60984
document.converter.mxn.value = document.converter.dollar.value * 13.2436
document.converter.jpy.value = document.converter.dollar.value * 102.490
}

</script>

</head>
<body>

<form name="converter">
<table border="0">

<td>Dollar Amount: </td><td><input type="text" name="dollar"
onChange="usdfunc()" /></td>
</table>

 <br>


Please select a currency type:
<select id="select">
<option value="eur" onChange="eurfunc()">Euro</option> 
<option value="mxn" onChange="mxnfunc()">Mexican Peso</option>
<option value="gbp" onChange="gbpfunc()">British Pound</option>
<option value="jpy" onChange="jpyfunc()">Japanese Yen</option>
</select>


<br><br>

New Currency:$ <br>
<input id="Calculate" type="button" value="Calculate"
onclick="usdfunc();" />


</form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我编辑了您的代码,以便在选择框中有一个默认选项和说明,并且更改该选择框的值会调用usdfunc(event),而不需要按下按钮的额外步骤。 We pass in the <select> event并使用event.target.value访问函数中的选择值,然后将其存储在targetCurrency变量中。

switch用于计算相应的转化率。

p元素位于文档的底部。最后,我们使用document.getElementById()引用它,然后分配它innerHTML(我们希望在标记之间存在的文本,在这种情况下)

&#13;
&#13;
function usdfunc(event){
  
  var targetCurrency = event.target.value;
  
  var conversion;
  var dollarValue = document.converter.dollar.value;
  
  switch (targetCurrency) {
    case "eur":
      conversion = dollarValue * 0.73640;
      break;
    case "mxn":
      conversion = dollarValue * 0.60984;
      break;
    case "gbp":
      conversion = dollarValue * 13.2436;
      break;
    case "jpy":
      conversion = dollarValue * 102.490;
      break;
  }
  
  var output = document.getElementById("output");
  output.innerHTML = "$" + dollarValue + " = " + targetCurrency + " " + conversion;

}
&#13;
<form name="converter">
<label>Dollar Amount: <input type="text" name="dollar"></label> 
 <br>
 <br>


Please select a currency type:
<select id="select" onchange="usdfunc(event);">
<option selected disabled>Select Currency</option>
<option value="eur" >Euro</option> 
<option value="mxn" >Mexican Peso</option>
<option value="gbp" >British Pound</option>
<option value="jpy" >Japanese Yen</option>
</select>


<br><br>


<p id="output"></p>
&#13;
&#13;
&#13;

事后补充:如果您想使用正确的货币符号,请在线获取符号,然后在每个switch case中抓取符号,将targetCurrency重新分配给包含该符号的字符串

case "eur":
  conversion = dollarValue * 0.73640;
  targetCurrency = "€";
  break;

PLNKR: http://plnkr.co/edit/GT65OEdYIv0oyR96BliX?p=preview