gpt4 book ai didi

javascript - 选择和取消选择某个单选按钮时切换元素可见性

转载 作者:行者123 更新时间:2023-12-01 01:46:30 28 4
gpt4 key购买 nike

我已经成功地在单选按钮选择上显示元素,但是当我选择组中的任何其他单选按钮时,该元素仍然可见。我错过了什么?

element.style.display = "none"使用普通 JavaScript 隐藏元素的惯用方法?

function showApples() {
const form = document.querySelector("form");
const apples = form.elements["apples"];
const appleCultivars = form.querySelector("fieldset:nth-of-type(2)");

apples.addEventListener("click", showApples);

if (apples.checked) {
appleCultivars.style.display = "";
} else {
appleCultivars.style.display = "none";
}
}
<body onLoad="showApples()">
<form>
<fieldset>
<legend>Fruits</legend>
<label><input type="radio" name="fruits" id="apples">Apples</label>
<label><input type="radio" name="fruits" id="oranges">Oranges</label>
<label><input type="radio" name="fruits" id="bananas">Bananas</label>
</fieldset>

<fieldset>
<legend>Apples</legend>
<label><input type="radio" name="apple" id="braeburn">Braeburn</label>
<label><input type="radio" name="apple" id="macoun">Macoun</label>
<label><input type="radio" name="apple" id="cortland">Cortland</label>
</fieldset>
</form>
</body>

我知道 Stack Overflow 上有类似的问题和答案,但没有一个看起来很优雅,也不是用 jQuery 编写的。

最佳答案

看看以下内容:

const fruits = Array.from( document.getElementsByName('fruits'));
const fields = Array.from( document.getElementsByTagName('fieldset'));

fields[1].style.display = 'none';

fruits.forEach( fruit => {
fruit.addEventListener('click', () => {
if(fruit.value == 'apples') {
fields[1].style.display = 'block';
} else {
fields[1].style.setProperty('display', 'none'); // or fields[1].style.display = 'none';
}
});
});
<form>
<fieldset>
<legend>Fruits</legend>
<label><input type="radio" name="fruits" value="apples">Apples</label>
<label><input type="radio" name="fruits" value="oranges">Oranges</label>
<label><input type="radio" name="fruits" value="bananas">Bananas</label>
</fieldset>

<fieldset>
<legend>Apples</legend>
<label><input type="radio" name="apple" value="braeburn">Braeburn</label>
<label><input type="radio" name="apple" value="macoun">Macoun</label>
<label><input type="radio" name="apple" value="cortland">Cortland</label>
</fieldset>
</form>

关于javascript - 选择和取消选择某个单选按钮时切换元素可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51911492/

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