我如何确保if else语句仅在javascript中准确条件为真时才有效?



我有一个if/else语句,如果鸡复选框被选中,它返回一个图像,但是,如果你选中了鸡复选框和另一个,它仍然显示图像,我怎么能设置语句只显示图像,只有当鸡复选框被选中?

代码如下:

if (chicken.checked == true) {
document.getElementById("image").style.visibility = "visible";
} else {  
return document.getElementById("error").innerHTML = "*Please mark any of checkbox";  
} 

如果您想仅在chicken复选框被选中时显示图像,那么您可能应该在If/else语句中测试所有其他复选框的值。

在本例中,图像最初是隐藏的。复选框上的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>

最新更新