我在WordPress的一個BMI計算器,那得到的將的Javascript:獲取類型錯誤 - 元素爲null
類型錯誤:
result is null and health is 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>
其實小提琴中的代碼是:'window.onlo ad = function(){/ *您的腳本* /};' – Andreas