首页 > 解决方案 > 我正在尝试编写一个 BMI 计算器和错误“未捕获的类型错误:无法设置未定义的属性 'src'”我很新,这不是最终的

问题描述

我没有添加任何图片,因为错误不断弹出。我已经尝试了我所知道的一切(不是很多),我需要帮助。Javascript 不允许我将图片添加到我的表格中。

function onCalculate() {
  var option1 = document.getElementById("frmKgM").checked;
  var option2 = document.getElementById("frmLbInches").checked
  var bmiWeight = document.getElementById("frmWeight").value;
  var bmiHeight = document.getElementById("frmHeight").value;
  var result
  var resultColor
  var final
  var bmiResult
  var img
  var image
  var floatWeight = parseFloat(bmiWeight);
  var floatHeight = parseFloat(bmiHeight);
  
  if (option1) {
    final = floatWeight / (floatHeight * floatHeight);
  } else {
    final = 703 * floatWeight / (floatHeight * floatHeight);
  }
  
  if (final <= 18.5) {
    result = "UnderWeight"
    image = < img src = "BMI/BMI/bmi_underweight.png" / >
  } else if (final >= 18.5 && final <= 24.9) {
    result = "Normal weight"
  } else if (final >= 25 && final <= 29.9) {
    result = "Obese"
  } else if (final >= 30) {
    result = "Extremely Obese"
  }

  if (final >= 18.5 && final <= 24.9) {
    resultColor = "<h3 style= 'color:blue;'>" + final + "</h3>"
  } else {
    resultColor = "<h3 style= 'color:red;'>" + final + "</h3>"
  }

  bmiResult = document.getElementById("idBMI").innerHTML = "Your Bmi is " + resultColor + result;
  bmiTD = document.getElementById('bmiTD');
  bmiTD.innerHTML += bmiResult
}
<table id="bmiTable" border="1" width="100%" cellspacing="5px" cellpadding="3px">
  <tr>
    <td colspan="2">
      <p style="text-align: center;">
        <img src="BMI/BMI/bmi.png" width="100" length="100" style="vertical-align:middle;" /> BMI Calculator
      </p>
    </td>
    <td id="image" rowspan="5"></td>
  </tr>
  
  <tr>
    <td>
      select operation
    </td>
    <td>
      <input type="radio" id="frmKgM" name="BMI" value="option1">kg/m;
      <input type="radio" id="frmLbInches" name="BMI" value="option2">lb/inches;<br>
    </td>
  </tr>

  <tr>
    <td>
      Enter your weight:
    </td>
    <td>
      <input type="text" id="frmWeight"><br>
    </td>
  </tr>

  <tr>
    <td>
      Enter your height:
    </td>
    <td>
      <input type="text" id="frmHeight"><br>
    </td>
  </tr>

  <tr>
    <td id="bmiTD" colspan="2"></td>
  </tr>
</table>

<button onclick="onCalculate()">Caculate</button><br>
<div id="idBMI"></div>

我不知道我哪里出错了。此外,一切都应该是纯 JavaScript,而不是使用 JQuery 或其他任何东西。我知道图像是 html 格式,但这是我知道如何做的唯一方法。

标签: javascript

解决方案


推荐阅读