.trim()为什么不和我一起工作?

时间:2014-03-09 20:32:30

标签: javascript html

我无法让这些javascript工作。每当我尝试它时,我的div中什么都不输入。它只是添加了?weight = NumberInputed& measure = lbsOrkgs& 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()函数,它会完美地执行,除非它不会识别与“lbs”或“kgs”类似的东西。这里发生了什么?

1 个答案:

答案 0 :(得分:0)

此处: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;
    }