【发布时间】:2023-02-24 13:29:03
【问题描述】:
我正在尝试建立一个测试网站,基本上说:如果您选择花生复选框,这里是一个免费的花生网站。如果您选择腰果,这里有一个免费提供腰果的网站。如果您同时选择两者,这里是一个免费提供花生和腰果的网站。 (将来,我会为其他食物添加其他复选框,然后进行各种组合)但是,我陷入了最后一部分 - 如果两个复选框都被选中,则尝试返回唯一信息。
这是我放在一起的代码。没有最后一个 else if 语句,它可以工作。但是我不确定如果要使它完全发挥作用,我需要对最后一个 else 做什么。感谢这里的任何指导!
function myFunction() {
if (document.getElementById("peanuts").checked) {
document.write(
"<p> You have selected Peanuts. Here's a peanut-free recipe:"
);
} else if (document.getElementById("cashews").checked) {
document.write(
"<p> You have selected Cashews. Here's a cashew-free recipe:"
);
} else if (document.getElementById("dairy").checked) {
document.write(
"<p> You have selected Dairy. Here's a dairy-free recipe:"
);
} else if (
document.getElementById("peanuts").checked &&
document.getElementById("cashews").checked
) {
document.write("<p> You have selected Both. Here's a nut-free recipe:");
}
}
<input type="checkbox" name="peanuts" id="peanuts" />Peanuts<br />
<input type="checkbox" name="cashews" id="cashews" />Cashews<br />
<input type="checkbox" name="dairy" id="dairy" />Dairy<br />
<button id="myButton" type="button" value="getValue" onclick="myFunction()">
Get Value
</button>
【问题讨论】:
-
您只需要在 if-else 树中将花生和腰果选项移到更高的位置,使其位于仅花生和仅腰果选项之前。
标签: javascript html