gpt4 book ai didi

javascript - 转换重量,数值不显示

转载 作者:行者123 更新时间:2023-11-30 14:31:53 26 4
gpt4 key购买 nike

我正在创建这个简单的重量转换器,但我在文本字段中显示值时遇到了一个小问题。我希望在我输入公斤的字段中返回结果。

我做错了什么?

目前我正在尝试将公斤转换为克

function submitF() {
const option1 = document.querySelector("#option1").value;
const option2 = document.querySelector("#option2").value;
var inputField = document.querySelector("#weightarea").value;
var kgToGram = inputField * 1000;



if (option1 === "Kilo" && option2 === "Grams") {
inputField = kgToGram;

}
}
<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>

<body>

<input id="weightarea" type="number" placeholder="value.....">
<input type="button" value="submit" onclick="submitF()"><br>
<select id="option1">
<option>Kilo</option>
<option>Pounds</option>
<option>Grams</option>
</select>

<p>to</p>

<select id="option2">
<option>Kilo</option>
<option>Pounds</option>
<option>Grams</option>
</select>




<script src="java2.js"></script>

</body>

</html>

最佳答案

var inputfield = document.querySelector("#weightarea").value;
inputfield = kgToGram;

...与...不同

document.querySelector("#weightarea").value = kgToGram;

我相信您希望 inputfield 成为引用,但事实并非如此。您当前的代码只是声明一个变量并使用输入值对其进行初始化。

上面的第二个例子实际上设置了输入的值。

见下文:

function submitF() {
const option1 = document.querySelector("#option1").value;
const option2 = document.querySelector("#option2").value;
var inputField = document.querySelector("#weightarea").value;
var kgToGram = inputField * 1000;

if (option1 === "Kilo" && option2 === "Grams") {
document.querySelector("#weightarea").value = kgToGram;
}
}
<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>

<body>

<input id="weightarea" type="number" placeholder="value.....">
<input type="button" value="submit" onclick="submitF()"><br>
<select id="option1">
<option>Kilo</option>
<option>Pounds</option>
<option>Grams</option>
</select>

<p>to</p>

<select id="option2">
<option>Kilo</option>
<option>Pounds</option>
<option>Grams</option>
</select>




<script src="java2.js"></script>

</body>

</html>

关于javascript - 转换重量,数值不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51030531/

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