gpt4 book ai didi

javascript - 摄氏度和华氏度转换器 - JavaScript

转载 作者:可可西里 更新时间:2023-11-01 13:09:46 26 4
gpt4 key购买 nike

我想制作一个包含两个文本框的网页,一个是摄氏度框,一个是华氏度框。在它们之间,有一个转换按钮,可以将摄氏温度转换为华氏温度,将华氏温度转换为摄氏温度。如果任一框中都有字母,我想取消转换并弹出警告“请输入数字!”到目前为止,我还没有弄清楚如何获得警报,当我在摄氏框中键入数字时,它总是在同一个框中显示数字 -18。华氏度很好。

HTML:

<html>
<head>
<title>Temparature Converter</title>
<script type="text/javascript" src="tempconversion.js"></script>
</head>
<body>
Celsius: <input id="c" onkeyup="convert('C')">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
Fahrenheit: <input id="f" onkeyup="convert('F')">
</body>
</html>

JavaScript:

function convertTemp(degree) {
if (degree == "C") {
F = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(F);
} else {
C = (document.getElementById("f").value -32) * 5 / 9;
document.getElementById("c").value = Math.round(C);
}
}

注意:我从 W3Schools 获得了一些代码,所以我认为 onkeyup convert 有点有趣。如果可能,请通知我它必须如何更改以及 JavaScript。

最佳答案

不需要 onkeyup 属性,因为它们是来自 W3Schools 的原始代码旨在在输入值时立即更新值。

我确实修改了功能以清除原始值,这样转换按钮就可以通过简单的代码双向工作。

这里有一个快速的 JavaScript 来完成这项工作:

function convertTemp() {
// Set the initial variables for c (Celsius) and f (Fahrenheit)
var c = document.getElementById('c'), f = document.getElementById('f');
// Test if there is a value for Celsius
if(c.value != '') {
// Set the value for Fahrenheit
f.value = Math.round(c.value * 9 / 5 + 32);
// Clear the value for Celsius
c.value = '';
// If there isn't a value for Celsius
} else {
// Set the value for Celsius
c.value = Math.round((f.value - 32) * 5 / 9);
// Clear the value for Fahrenheit
f.value = '';
}
}

及其附带的 HTML:

Celcius:<input id="c">&nbsp;&nbsp;&nbsp;
Fahrenheit:<input id="f">&nbsp;&nbsp;&nbsp;
<button type="button" id="convert" onclick="convertTemp()">Convert</button>

可在:http://jsfiddle.net/bhz6uz54/进行测试

关于简单的代码需要记住一些事情,像这样,没有什么可以验证提供的值是否可以接受。一个小的正则表达式可以作为验证,但它的实现方式取决于你想如何标记问题。

关于javascript - 摄氏度和华氏度转换器 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26046474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com