我正在尝试做一个摄氏度/华氏度转换计算器,每次转换都有一个按钮,结果显示在相应的文本框中。我一定在这里遗漏了一些明显的东西......我是 javascript 的新手,只是不明白。这是我到目前为止所做的:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8"/>
<title>Convert Fahrenheit and Celsius</title>
<script type="text/javascript">
<!--
function convertToC() {
var fTempVal = parseFloat(document.getElementById('fTemp').value);
var cTempVal = (fTempVal - 32) * (5/9);
document.getElementById('cTemp').value = cTempVal;
}
function convertToF() {
var cTempVal = parseFloat(document.getElementById('cTemp').value);
var fTempVal = (cTempVal * (9/5)) + 32;
document.getElementById('fTemp').value = fTempVal;
}
// -->
</script>
</head>
<body>
<form name="conversionForm">
<table border="1">
<tbody>
<tr>
<td>Fahrenheit</td>
<td><input name="fTemp" type="text"/></td>
<td><button onclick="convertToC">Convert to Celsius</button></td>
</tr>
<tr>
<td>Celsius</td>
<td><input name="cTemp" type="text"/></td>
<td><button onclick="convertToF">Convert to Fahrenheit</button></td>
</tr>
</form>
</tbody>
</table>
</body>
</html>
最佳答案
你有一些错误。请参阅此更正后的 jsFiddle example .
- 您的输入框缺少您尝试使用
document.getElementById
引用的 ID - 您的 HTML 未正确关闭。
- 您的按钮缺少类型,这使得它们 default to submit当你真的想要按钮时
- 为防止表单实际被提交,您应该返回 false。
JavaScript
function convertToC() {
var fTempVal = parseFloat(document.getElementById('fTemp').value);
var cTempVal = (fTempVal - 32) * (5 / 9);
document.getElementById('cTemp').value = cTempVal;
return false;
}
function convertToF() {
var cTempVal = parseFloat(document.getElementById('cTemp').value);
var fTempVal = (cTempVal * (9 / 5)) + 32;
console.log(fTempVal);
document.getElementById('fTemp').value = fTempVal;
return false;
}
HTML
<form name="conversionForm">
<table border="1">
<tbody>
<tr>
<td>Fahrenheit</td>
<td>
<input name="fTemp" id="fTemp" type="text" />
</td>
<td>
<button type="button" onclick="convertToC();return false">Convert to Celsius</button>
</td>
</tr>
<tr>
<td>Celsius</td>
<td>
<input name="cTemp" id="cTemp" type="text" />
</td>
<td>
<button type="button" onclick="convertToF();return false">Convert to Fahrenheit</button>
</td>
</tr>
</tbody>
</table>
</form>
关于javascript - 基本的javascript华氏/摄氏计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15122347/