转换重量,该值不显示

时间:2018-06-25 19:21:32

标签: javascript html

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

我在做什么错了?

此刻我正尝试将千克转换为克

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>

2 个答案:

答案 0 :(得分:1)

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>

答案 1 :(得分:1)

进行转换后,您无需设置输入字段的值。相反,您只是在告诉inputField javascript变量来保存kgToGram的值。

function submitF() {
  const option1 = document.querySelector("#option1").value;
  const option2 = document.querySelector("#option2").value;
  var inputField = document.querySelector("#weightarea").value; // retrieving the value at that point-in-time.  Not the entire element.
  var kgToGram = inputField * 1000;



  if (option1 === "Kilo" && option2 === "Grams") {
    // wrong ... inputField = kgToGram;
    document.querySelector("#weightarea").value = kgToGram; // re-assign the value of the input element
  }


}