Javascript:获取Typeerror - 元素为空

时间:2017-06-28 08:53:52

标签: javascript html wordpress typeerror

我在Wordpress中有一个BMI计算器,它是

类型错误:

  

结果为null和   健康是空的

计算器工作正常https://jsfiddle.net/2au9y34x/2/ 但不要使用Wordpress。我已将脚本放在页脚中,以便首先读取HTML,这样就不会出现问题。 任何人都可以帮忙解决这个问题吗?

Javascript是:

<script type='text/javascript'>
  var form = document.querySelector('form[name=bmi]');
  var onSubmit = function(event) {

    event.preventDefault();
    var healthMessage;

    var result = form.querySelector('.result');
    var health = form.querySelector('.health');

    var weight = parseInt(form.querySelector('input[name=weight]').value, 10);
    var height = parseInt(form.querySelector('input[name=height]').value, 10);

    var bmi = (weight / (height / 100 * height / 100)).toFixed(1);

    if (bmi < 18.5) {
      healthMessage = 'undervægtig';
    } else if (bmi > 18.5 && bmi < 25) {
      healthMessage = 'normal vægtig';
    } else if (bmi > 25) {
      healthMessage = 'overvægtig';
    }
    result.innerHTML = bmi;
    health.innerHTML = healthMessage;
  }
  form.addEventListener('submit', onSubmit, false);
</script>

HTML是:

<form name="bmi">
  <h1>Mål dit BMI:</h1>
  <label>
    <input type="text" name="weight" id="weight" placeholder="Vægt (kg)">
    <input type="text" name="height" id="height" placeholder="Højde (cm)">
    <input type="submit" name="submit" id="submit" value="Udregn BMI">
    </label>
  <div class="calculation">
    <div>
      Dit BMI er: <span class="result"></span>
    </div>
    <div>
      Dette betyder at du er: <span class="health"></span>
    </div>
  </div>
</form>

1 个答案:

答案 0 :(得分:0)

在表单

的结束标记之后添加javascript

或者你可以试试这个

window.onload = function() {
 var form = document.querySelector('form[name=bmi]');
 var onSubmit = function(event) {

event.preventDefault();
var healthMessage;

var result = form.querySelector('.result');
var health = form.querySelector('.health');

var weight = parseInt(form.querySelector('input[name=weight]').value, 10);
var height = parseInt(form.querySelector('input[name=height]').value, 10);

var bmi = (weight / (height / 100 * height / 100)).toFixed(1);

if (bmi < 18.5) {
  healthMessage = 'undervægtig';
} else if (bmi > 18.5 && bmi < 25) {
  healthMessage = 'normal vægtig';
} else if (bmi > 25) {
  healthMessage = 'overvægtig';
}
result.innerHTML = bmi;
health.innerHTML = healthMessage;
}
form.addEventListener('submit', onSubmit, false);
}