三个按钮循环绑定点击事件,控制另外三个盒子的显示隐藏
时间: 2024-05-15 21:18:19 浏览: 17
很好的问题,可以通过以下的代码实现:
```html
<!-- HTML部分 -->
<button class="btn" data-target="box1">按钮1</button>
<button class="btn" data-target="box2">按钮2</button>
<button class="btn" data-target="box3">按钮3</button>
<div class="box" id="box1">盒子1</div>
<div class="box" id="box2">盒子2</div>
<div class="box" id="box3">盒子3</div>
```
```javascript
// JS部分
const buttons = document.querySelectorAll('.btn');
const boxes = document.querySelectorAll('.box');
buttons.forEach(button => {
button.addEventListener('click', function() {
const target = this.dataset.target;
boxes.forEach(box => {
if (box.getAttribute('id') === target) {
box.style.display = 'block';
} else {
box.style.display = 'none';
}
});
});
});
```
上面的代码中,我们首先通过 `querySelectorAll` 方法获取了所有的按钮和盒子,并且通过 `forEach` 方法对每一个按钮添加了点击事件。当按钮被点击时,我们获取其 `data-target` 属性的值,并且通过 `forEach` 方法遍历所有盒子,如果盒子的 `id` 等于目标值,则将其显示,否则隐藏。这样,点击按钮就可以控制对应的盒子的显示和隐藏了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)