gpt4 book ai didi

javascript - 表格计算JS(单选)

转载 作者:行者123 更新时间:2023-11-30 18:04:23 30 4
gpt4 key购买 nike

HTML 部分,只是我代码的一部分:

    <ul>
<li>HP:<input type="text" id="hp" size="3" maxlength="3"> </li>
<li>SP:<input type="text" id="sp" size="3" maxlength="3"> </li>
<li>EA:<input type="text" id="ea" size="3" maxlength="3"> </li>
<li>ED:<input type="text" id="ed" size="3" maxlength="3"> </li>
<li>PA:<input type="text" id="pa" size="3" maxlength="3"> </li>
<li>PD:<input type="text" id="pd" size="3" maxlength="3"> </li>
</ul>
<div class="train">
<h3>Add Trainer:</h3>
<ul>
<li>HP:<input type="radio" name="at" id="ahp"></li>
<li>SP:<input type="radio" name="at" id="asp"></li>
<li>EA:<input type="radio" name="at" id="aea"></li>
<li>ED:<input type="radio" name="at" id="aed"></li>
<li>PA:<input type="radio" name="at" id="apa"></li>
<li>PD:<input type="radio" name="at" id="apd"></li>
</ul>
</div>

JS:(问题出在哪里)

function trener1() {
var test1 = document.getElementById('ahp').checked,
x = Number(document.form.hp.value),
xSum = 0;
if (test1) {
xSum = x + x * 0.1;
} else {
xSum = x - x * 0.1;
}
document.form.hp.value = xSum;
};

function trener2() {
var test2 = document.getElementById('asp').checked,
x = Number(document.form.sp.value),
xSum = 0;
if (test2) {
xSum = x + x * 0.1;
} else {
xSum = x - x * 0.1;
}
document.form.sp.value = xSum;
};

function trener3() {
var test3 = document.getElementById('aea').checked,
x = Number(document.form.ea.value),
xSum = 0;
if (test3) {
xSum = x + x * 0.1;
} else {
xSum = x - x * 0.1;
}
document.form.ea.value = xSum;
};

function trener4() {
var test4 = document.getElementById('aed').checked,
x = Number(document.form.ed.value),
xSum = 0;
if (test3) {
xSum = x + x * 0.1;
} else {
xSum = x - x * 0.1;
}
document.form.ed.value = xSum;
};

function trener5() {
var test5 = document.getElementById('apa').checked,
x = Number(document.form.pa.value),
xSum = 0;
if (test5) {
xSum = x + x * 0.1;
} else {
xSum = x - x * 0.1;
}
document.form.pa.value = xSum;
};

function trener6() {
var test6 = document.getElementById('apd').checked,
x = Number(document.form.pd.value),
xSum = 0;
if (test6) {
xSum = x + x * 0.1;
} else {
xSum = x - x * 0.1;
}
document.form.pd.value = xSum;
};

所以是的,问题是如果我更改我应该更改的选项,它不会减去已添加的值。问题出在哪里?

最佳答案

问题是

document.form.ea.value

必须是

document.forms.formName.ea.value

您忘记指定表单的名称。它也应该是 document.forms

同时尝试优化你的代码,像这样的东西应该可以代替所有这些重复的函数:

var radio = document.getElementsByName('at');

for (var i = radio.length; i--;) {
radio[i].onchange = function () {
var field = document.getElementById(this.id.substr(1)),
x = Number(field.value),
xSum = 0;
if (this.checked) {
xSum = x + x * 0.1;
} else {
xSum = x - x * 0.1;
}
field.value = xSum;
};
}

并删除 onclick 处理程序:

<li>SP:<input type="radio" name="at" id="asp"></li>
...

关于javascript - 表格计算JS(单选),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16175523/

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