当我仅使用 JavaScript 单击相应按钮时,如何显示和隐藏多个 div?

问题描述 投票:0回答:1

我试图在用户单击按钮时显示和隐藏 div。 我也想更改按钮的图像源,但我的头已经爆炸了。所以,一次只做一件事。

我知道如何一一隐藏和显示 div,但我正在努力尝试自动化该过程。

以下是页面截图(手机版): Here I am!

按钮有两类:

class="button button_0"
class="button button_1"
等等

以下是div的iD模型:

answer_0
answer_1
等等

main.js:

const buttonList = document.querySelectorAll('.button');
const iconList = document.querySelectorAll(".icon");
const div = document.querySelectorAll('.container__answer');
const imgArray = ["assets/images/icon-minus.svg", "assets/images/icon-plus.svg"];

//functions


function changeImgSource () {
    if (idIcon.src.match(imgArray[0])) {
        idIcon.src = imgArray[1];
    } else if (idIcon.src.match(imgArray[1])) {
        idIcon.src = imgArray[0];
    }
}

function showHide () {
    if (idAnswer.style.display === "none") {
        idAnswer.style.display = block;
    } else {
        idAnswer.style.display = none;
    }
}

function all () {
    showHide ();
    changeImgSource ();
}

//i dont know :,(

let count = 0;


//I'll change to "for". Just think it's easier to read as a js newbie.

while (count < buttonList.length) {
    const button = buttonList[count];
    const classButton = button.classList[1];
    const idIcon = `#icon_${classButton}`;
    const idAnswer =`#answer_${classButton}`;

    button.onclick = function () {
        showHide(idAnswer);
    }

    count++;
}


这是 GitHub 项目。是免费的前端导师挑战,所以我认为共享没有问题。 GitHub 项目

由于 Opera 的控制台不断重复“idAnswer”未定义,我尝试更改代码的顺序。但至少它本身并没有多大帮助。

最后,Opera 的检查员不断重复消息:“Uncaught TypeError: Cannot read properties of undefined (reading 'display')”

我也尝试过一些更高级的代码,但我不太理解,最终没有工作。

javascript arrays automation show-hide
1个回答
0
投票

我的建议是不要使用 ID,而是使用 closest()querySelector()。这样,它就可以扩展和重用。这也导致您使用类来管理显示/隐藏,而不是直接设置样式属性(如 style.display='block')。在这里,我只是给单元格着色,但是您可以轻松地将其更改为显示隐藏情况。这是一个例子

document.addEventListener('DOMContentLoaded', _ => {
  let allBlocks = document.querySelectorAll('.block button')
  allBlocks.forEach(btn => {
    // first add an event listener to the buttons
    btn.addEventListener('click', e => {
      // deselect the currently selected one
      // we put in the ? in case it doesn't exist yet
document.querySelector('.block.active')?.classList.remove('active');
      // now activate the one I clicked on - e.target here represents the button clicked
      e.target.closest('.block').classList.add('active');
    })
  })
})
.block {
  padding: 10px;
  border: 1px solid #999;
}

.active {
  background: yellow;
}
<div class='blocks'>
  <div class='block'>
    <button>Click me</button>
  </div>
  <div class='block'>
    <button>Click me</button>
  </div>
  <div class='block'>
    <button>Click me</button>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.