我正在使用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>
&#13;
<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>
&#13;
答案 0 :(得分:2)
Try this:
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>
You need to get the value of the input field, with document.getElementById("kgid").value
and you need to add onsubmit="return false"
to your form as well because your form doesn't suppose to send its data to anywhere.
答案 1 :(得分:0)
你也可以在你的函数中使用parseInt。
浏览器有时将数字解释为字符串,从文本字段输入,导致NaN
<script>
function Convert(v) {
var valNum = parseInt(v);
//or var valNum = Number(v);
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>