问题描述
我正在尝试创建一个货币转换器,该货币转换器可在更改时在几种不同的货币之间进行转换.它使用一些预定的汇率.输入框显示出来,但是所有的javascript似乎都不起作用.有帮助吗?
I'm trying to make a currency converter that converts between several different currencies on change. It uses some pre-determined exchange rates. Input boxes display, but none of the javascript seems to work. Any help?
使用更新的代码进行编辑.仍然不会转换任何东西.
Edited with updated code. Still does not convert anything.
HTML正文:
<body onload="init()">
<input type="text" id="GBP" size="10" value="0" onchange="gbp()"/>
<label for="GBP"> GBP </label>
</br>
<input type="text" id="USD" size="10" value="0" onchange="usd()" />
<label for="USD"> USD </label>
</br>
<input type="text" id="EUR" size="10" value="0" onchange="eur()" />
<label for="EUR"> EUR </label>
</br>
<input type="text" id="CAD" size="10" value="0" onchange="cad()" />
<label for="CAD"> CAD </label>
</br>
<input type="text" id="AUD" size="10" value="0" onchange="aud()" />
<label for="AUD"> AUD </label>
</body>
JavaScript代码:
Javascript code:
var gbp, usd, eur, cad, aud;
function init()
{
gbp = document.getElementById("GBP");
usd = document.getElementById("USD");
eur = document.getElementById("EUR");
cad = document.getElementById("CAD");
aud = document.getElementById("AUD");
}
function gbp()
{
usd.value = parseFloat(gbp.value) * 0.49246;
eur.value = parseFloat(gbp.value) * 0.69714;
cad.value = parseFloat(gbp.value) * 0.50221;
aud.value = parseFloat(gbp.value) * 0.43497;
}
function eur()
{
gbp.value = parseFloat(eur.value) * 1.43448;
usd.value = parseFloat(eur.value) * 0.70641;
cad.value = parseFloat(eur.value) * 0.72037;
aud.value = parseFloat(eur.value) * 0.62382;
}
function cad()
{
gbp.value = parseFloat(cad.value) * 1.99169;
usd.value = parseFloat(cad.value) * 0.98054;
eur.value = parseFloat(cad.value) * 1.38814;
aud.value = parseFloat(cad.value) * 0.86613;
}
function aud()
{
gbp.value = parseFloat(aud.value) * 2.29964;
usd.value = parseFloat(aud.value) * 1.13262;
eur.value = parseFloat(aud.value) * 1.60329;
cad.value = parseFloat(aud.value) * 0.88297;
}
function usd()
{
gbp.value = parseFloat(usd.value) * 2.03032;
eur.value = parseFloat(usd.value) * 1.41544;
cad.value = parseFloat(usd.value) * 1.01941;
aud.value = parseFloat(usd.value) * 0.88297;
}
推荐答案
您需要从 initialize
函数中删除 var
语句,并将其添加到此函数上方:
You need to remove var
statements from initialize
function and add them above this function:
var gbp, usd, eur, cad, aud;
function init()
{
gbp = document.getElementById("GBP");
usd = document.getElementById("USD");
eur = document.getElementById("EUR");
cad = document.getElementById("CAD");
aud = document.getElementById("AUD");
//...
在这种情况下,变量 gbp,usd,eur,cad,aud
将在其他函数范围中可见.
In this case variables gbp, usd, eur, cad, aud
will be visible in other functions scopes.
可能您需要阅读有关变量和范围的更多信息.例如,在 MDN 中.范围和闭包在JS中非常重要.
Probably you need to read more about variables and scopes. For example at MDN. Scopes and closures are very important in JS.
这篇关于HTML/Javascript货币转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!