如果选中了“鸡”复选框,则有一个if / set语句返回图像,但是,如果选中“鸡”复选框,而另一个“鸡”复选框仍然显示图像,那么如果选中“鸡”复选框,如何将该语句设置为只显示图像?
守则如下:
if (chicken.checked == true) {
document.getElementById("image").style.visibility = "visible";
} else {
return document.getElementById("error").innerHTML = "*Please mark any of checkbox";
} 发布于 2021-08-07 08:14:43
最初,在本例中,图像是隐藏的。filter (filter返回数组以便检查其长度)在选中的框上。如果复选框的长度为1,并且是小鸡框,则从图像中删除隐藏类,否则将其添加回。
注意:我向容器中添加了一个单击监听器,而没有在每个复选框中添加一个,是为了利用事件委托。容器从盒子中捕捉事件,因为它们会将DOM抛出。这就是为什么我们需要检查被点击的元素是否是一个输入(使用nodeName)。
// Cache some elements
const chicken = document.querySelector('#chicken');
const container = document.querySelector('#container');
const boxes = document.querySelectorAll('input[type="checkbox"]');
// Add a listener to the container
container.addEventListener('click', handleBox, false);
function handleBox(e) {
// Extract the nodeName, and the name of the
// element that's been checked
const { nodeName, name } = e.target;
// If it's an input
if (nodeName === 'INPUT') {
// `filter` on the checked boxes
// `[...boxes]` means convert the nodelist
// (which doesn't have array methods)
// to an array, so we can use `filter`
const checkedBoxes = [...boxes].filter(box => box.checked);
// If the number of checked boxes is 1,
// and it's the chicken box...
if (checkedBoxes.length === 1 && checkedBoxes[0].name === 'chicken') {
// ...remove the hidden class from the chicken div...
chicken.classList.remove('hidden');
} else {
// ...otherwise add the hidden class back
chicken.classList.add('hidden');
}
}
}.hidden { visibility: hidden; }<div id="container">
<input name="chicken" type="checkbox">
<label>Chicken</label><br/>
<input name="mongoose" type="checkbox">
<label>Mongoose</label><br/>
<input name="steve" type="checkbox">
<label>Steve</label><br/>
<input name="kookaburra" type="checkbox">
<label>Kookaburra</label><br/>
</div>
<br />
<div id="chicken" class="hidden">Chicken image</div>
发布于 2021-08-07 07:41:52
如果您希望只在选中“鸡”复选框时显示“图像”,则应该在if/else语句中测试所有其他复选框的值。
https://stackoverflow.com/questions/68690295
复制相似问题