gpt4 book ai didi

javascript - 在 javascript 中添加输入时未定义的输出

转载 作者:行者123 更新时间:2023-12-03 00:55:52 24 4
gpt4 key购买 nike

尝试制作 BMR 计算器作为家庭作业。我想我已经弄清楚了大部分内容,但我的输出字段中的输出为“未定义”。这是代码:

<input class="boks" placeholder="vekt i kg" id="vekt" type="text">

<input class="boks" placeholder="høyde i cm" id="hoyde" type="text">

<input class="boks" placeholder="alder" id="alder" type="text">

<button id="beregn" onclick="utregning()">Regn ut din BMR</button>

<input class="boks" placeholder="Din BMR" id="output" type="text"
readonly="true">

js:

var konstant = 66.5;

var vekt = parseInt(document.getElementById("vekt").value);

var vektutr = vekt*13.75;

var hoyde = parseInt(document.getElementById("hoyde").value);

var hoydeutr = hoyde*5.003;

var alder = parseInt(document.getElementById("alder").value);

var alderutr = alder*6.755;

var sum = +konstant + +vektutr + +hoydeutr - +alderutr;

function utregning() {

document.getElementById("output").value = sum;

}

最佳答案

您需要从函数内部的输入中获取所有值,因为函数外部的代码将在调用utregning之前执行,此时输入字段的值为空

var konstant = 66.5;



function utregning() {
var vekt = parseInt(document.getElementById("vekt").value);

var vektutr = vekt * 13.75;

var hoyde = parseInt(document.getElementById("hoyde").value);

var hoydeutr = hoyde * 5.003;

var alder = parseInt(document.getElementById("alder").value);

var alderutr = alder * 6.755;

var sum = +konstant + +vektutr + +hoydeutr - +alderutr;

document.getElementById("output").value = sum;

}
<input class="boks" placeholder="vekt i kg" id="vekt" type="text">

<input class="boks" placeholder="høyde i cm" id="hoyde" type="text">

<input class="boks" placeholder="alder" id="alder" type="text">

<button id="beregn" onclick="utregning()">Regn ut din BMR</button>

<input class="boks" placeholder="Din BMR" id="output" type="text" readonly="true"> js:

关于javascript - 在 javascript 中添加输入时未定义的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52842192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com