我设法在单选按钮选择上显示元素,但是当我选择组中的任何其他单选按钮时,该元素保持可见。我错过了什么?
是element.style.display = "none"
使用 vanilla 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句