我正在使用javascript创建重量转换。但不幸的是,我没有得到正确的输出,而是在必填字段中输入了NaN



<script>
function Convert(valNum) {
  document.getElementById("outputPounds").innerHTML=valNum*2.2046;
  document.getElementById("outputGrams").innerHTML=valNum*1000;
  document.getElementById("outputMilligrams").innerHTML=valNum*1000000;
  document.getElementById("outputUsTons").innerHTML=valNum*0.0011023;
  document.getElementById("outputOunces").innerHTML=valNum*35.274;
}
</script>

<form name="Weightconverter">
		<fieldset class="container">
		<label for="enterWeight" >Enter Weight in Kilogram: </label>
		<input type="text" id="kgid" name="enterWeight"/>
		<input  type="button" id="enterWeight" style="background-color:#069; width:100px; padding:5px; text-align:center" value="Convert"  onClick="Convert(this.value)"/>
		</fieldset>
        </p>
        <div class="container">
		<p>Pounds: <span id="outputPounds"></span></p>
		<p>Grams: <span id="outputGrams"></span></p>
		<p>Milligrams: <span id="outputMilligrams"></span></p>
		<p>UsTons: <span id="outputUsTons"></span></p>
		<p>Ounces: <span id="outputOunces"></span></p>
        </div>

最佳答案

尝试这个:




  function Convert() {
   var valNum = document.getElementById("kgid").value;

    document.getElementById("outputPounds").innerHTML=valNum*2.2046;
    document.getElementById("outputGrams").innerHTML=valNum*1000;
    document.getElementById("outputMilligrams").innerHTML=valNum*1000000;
    document.getElementById("outputUsTons").innerHTML=valNum*0.0011023;
    document.getElementById("outputOunces").innerHTML=valNum*35.274;
  }


 

<form name="Weightconverter" onsubmit="return false">
		<fieldset class="container">
		<label for="enterWeight" >Enter Weight in Kilogram: </label>
		<input type="text" id="kgid" name="enterWeight"/>
    <button id="enterWeight" style="background-color:#069; width:100px; padding:5px; text-align:center" onClick="Convert()">
        Convert
    </button>

		</fieldset>
        </p>
        <div class="container">
		<p>Pounds: <span id="outputPounds"></span></p>
		<p>Grams: <span id="outputGrams"></span></p>
		<p>Milligrams: <span id="outputMilligrams"></span></p>
		<p>UsTons: <span id="outputUsTons"></span></p>
		<p>Ounces: <span id="outputOunces"></span></p>
        </div>





您需要使用document.getElementById("kgid").value获取输入字段的值,并且还需要将onsubmit="return false"添加到表单中,因为表单不打算将其数据发送到任何地方。

10-01 09:23