gpt4 book ai didi

javascript - 为什么 .trim() 不能与我一起使用?

转载 作者:行者123 更新时间:2023-11-28 08:27:04 25 4
gpt4 key购买 nike

我无法让这段 javascript 正常工作。每当我尝试时,它都不会向我的 div 中输入任何内容。它只是将 ?weight=NumberInputed&measure=lbsOrkgs&submit=Submit 添加到 URL。

    <h2>How small must you be to become a black hole?</h2>
<form name="form1">
<input id="howMuch" type="number" name="weight" placeholder="How much do you weigh?">
<input type="radio" name="measure" value="lbs" checked="true">lbs
<input type="radio" name="measure" value="kgs">kgs
<input type="submit" name="submit" value="Submit" onClick="calc(); return false;">
</form>
<br/>
<div id="insert"><div/>
<script language="JavaScript" type="Text/JavaScript">
function calc() {
var speedOfLight = 299792458.0;
var gravityConstantYoctometre = 66738400000000.0;
var finalHeight = 0.0;
var weight = document.form1.weight.value;
var measure = document.form1.measure.value;
measure = measure.trim();

if (measure !== "kgs"){
weight *= 0.4536;
}

finalHeight = (4.0 * gravityConstantYoctometre * weight)/Math.pow(speedOfLight,2);
finalHeight = (finalHeight).toFixed(5);
var message = '<em>You would have to be ' + finalHeight + ' yoctometres (1 metre x 10<sup>-24</sup>) tall before you would become a black hole.</em>';
document.getElementById('insert').innerHTML = message;
}
</script>

如果没有 .trim() 函数,它可以完美执行,但它无法识别等于“磅”或“公斤”的度量。这里发生了什么?

最佳答案

这里:http://jsfiddle.net/dJJjr/1/

 function calc() {
var speedOfLight = 299792458.0;
var gravityConstantYoctometre = 66738400000000.0;
var finalHeight = 0.0;
var weight = document.getElementById("howMuch").value;
var radio = document.getElementsByName('measure');

var measure = ""
for(var i =0; i< radio.length; i++)
{
if(radio[i].checked)
measure = radio[i].value;
}
measure = measure.trim();
alert(measure); //For testing purpose
alert(weight); //For testing purpose
if (measure !== "kgs"){
weight *= 0.4536;
}

finalHeight = (4.0 * gravityConstantYoctometre * weight)/Math.pow(speedOfLight,2);
finalHeight = (finalHeight).toFixed(5);
var message = '<em>You would have to be ' + finalHeight + ' yoctometres (1 metre x 10<sup>-24</sup>) tall before you would become a black hole.</em>';
document.getElementById('insert').innerHTML = message;
}

关于javascript - 为什么 .trim() 不能与我一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22287772/

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