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

标签 javascript html if-statement categories

我需要修改下面的代码才能识别用户属于哪个类别。类别是:

  • 低于 18.5 体重不足
  • 18.5 至 25 正常
  • 25-30 超重
  • 肥胖超过 30 岁

最后我需要代码自动知道用户属于哪个类别并显示:这意味着您是(体重过轻、正常等)

谢谢。

<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>

最佳答案

将此行添加到您的 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;

关于javascript - 修改代码以识别 html 代码中的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21843321/

相关文章:

javascript - javascript 中有类似快速可选链接的东西吗?

javascript - 如何知道 Bootstrap 轮播是否由人转换?

html - Chrome 打印表格,有些行的高度是随机的?

html - 导航栏和标题在移动设备上无法正确缩放

sql - 我的中频条件在哪里?

if-statement - Gradle 仅在定义的属性上运行任务

r - dplyr mutate stringr str_detect 具有多个条件参数和相应的输出

javascript - 从 Rails Controller 获取浏览器 Cookie

javascript - Ajax调用-12019错误

html - 我如何在 TWebBrowser 中以 HTML 格式显示 rss 提要的输出?