修改代码以识别html代码中的类别

时间:2014-02-18 02:40:47

标签: javascript html if-statement categories

好的,所以我需要修改下面的代码,以便能够识别用户所在的类别。类别是:

  • 低于18.5体重不足
  • 18.5至25正常
  • 25-30超重
  • 超过30个Obese

然后在最后我需要代码自动知道用户所在的类别并显示:这意味着你是(体重不足,正常等)

谢谢。

<html>
<head>
    <title>BMI Calculator</title>
    <script type="text/javascript">
        function computeBMI()
        {
            //Obtain user inputs
            var height=Number(document.getElementById("height").value);
            varheightunits=document.getElementById("heightunits").value;
            var weight=Number(document.getElementById("weight").value);
            varweightunits=document.getElementById("weightunits").value;

            //Convert all units to metric
            if (heightunits=="inches") height/=39.3700787;
            if (weightunits=="lb") weight/=2.20462;

            //Perform calculation
            var BMI=weight/Math.pow(height,2);

            //Display result of calculation
            document.getElementById("output").innerText=Math.round(BMI*100)/100;
        }
    </script>
</head>
<body>
    <h1>Body Mass Index Calculator</h1>
    <p>Enter your height: <input type="text" id="height"/>
        <select type="multiple" id="heightunits">
            <option value="metres" selected="selected">metres</option>
            <option value="inches">inches</option>
        </select>
    </p>
    <p>Enter your weight: <input type="text" id="weight"/>
        <select type="multiple" id="weightunits">
            <option value="kg" selected="selected">kilograms</option>
            <option value="lb">pounds</option>
        </select>
    </p>
    <input type="submit" value="computeBMI" onclick="computeBMI();">
    <h1>Your BMI is: <span id="output">?</span></h1>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

在HTML中添加此行,可能在<h1>标记下方

<span id="id_here"></span>

只要它有id,任何其他元素都可以工作。

然后在你的JS中添加:

var writeThere = document.getElementById("id_of_the_element_below_h1");

if(ans < 18.5) {
   writeThere.innerText= "You are underweight";
} else if(ans > 18.5 && ans < 25) { 
   writeThere.innerText= "You are normal";
} else if(ans > 25 && ans < 30) { 
   writeThere.innerText= "You are overweight";
} else {
   writeThere.innerText= "You are obese";
}

您可能会问变量 ans 的位置,它可以就在这里:

var ans = Math.round(BMI*100)/100;
//Display result of calculation
 document.getElementById("output").innerText= ans;