我遇到了这个javascript的问题。这是一个例子
window.onload = initPage;
var euro;
var convert;
function initPage()
{
document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();
}
function calcAnswer()
{
//alert(document.getElementById("conversionType").value);
var value1 = document.getElementById("amount").value;
var conversionType = document.getElementById("conversionType").value;
//alert(conversionType);
if(var value = document.getElementById("conversionType").value=="polish");
document.getElementById("answer").value=(value1-32)/9*5;
else
document.getElementById("answer").value=value1*9/5+32;
}
这是html
<h1>Currency Converter</h1>
<form name="convert">
Choose which currency you would like to convert to the Euro:
<select id="conversionType">
<option value="polish">Polish Zloty</option>
<option value="ukraine">Ukraine Hryvnia</option>
</select>
</br>
</br>
<hr>
Amount:<input id="amount" type="text" />
<input id="convertButton" type="button" value="Convert->"/>
To:
<input id="answer" type="text" name="answer" readonly="readonly"/>
</form>
我正在使用一个旧的温度转换器,并没有改变那个部分,但即使那部分也没有用。
答案 0 :(得分:3)
首先,这两行是错误的:
document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();
将它们更改为:
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
您希望为onclick
和onchange
分配函数引用,而不是实际调用该函数并指定返回值。
然后,在if
中修复calcAnswer
语句,如下所示:
function calcAnswer()
{
var amount = document.getElementById("amount").value;
var conversionType = document.getElementById("conversionType").value;
var answerElement = document.getElementById("answer");
//alert(conversionType);
if(conversionType == "polish") {
answerElement.value = (amount-32)/9*5;
} else {
answerElement.value = amount*9/5+32;
}
}
答案 1 :(得分:0)
应该是
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
(没有parens)
您只需要引用该函数,而不是执行它。