如何使用单击事件侦听器制作按钮切换显示?

我有大约 20 个产品,每个产品都有一个按钮和描述框。我已经循环添加了一个单击事件侦听器,一旦单击按钮就会显示产品描述框。


我怎样才能让按钮也能够隐藏描述框(即切换显示)?


这是我的代码:


const descriptionBtn = document.querySelectorAll('.desc-btn');


descriptionBtn.forEach((btn) => {

  btn.addEventListener('click', (e) => {

    descriptionBox = btn.nextElementSibling;

    descriptionBox.style.display = "block";

  });

});


白板的微信
浏览 122回答 4
4回答

拉丁的传说

您可以使用按钮单击处理程序来切换描述文本上的类以切换其可见性。完整的工作示例:const descBtns = document.querySelectorAll('.desc-btn');descBtns.forEach((btn) => {&nbsp; btn.addEventListener('click', (e) => {&nbsp; &nbsp; descText = btn.nextElementSibling;&nbsp; &nbsp; descText.classList.toggle('show');&nbsp; });});.desc-btn {&nbsp; display: block;&nbsp; margin-bottom: 10px;}.desc {&nbsp; display: none;}.desc.show {&nbsp; display: block;}<button class="desc-btn">desc btn</button><p class="desc">description here</p><button class="desc-btn">desc btn 2</button><p class="desc">description here 2</p><button class="desc-btn">desc btn 3</button><p class="desc">description here 3</p>

智慧大石

为具有“隐藏背景”、“显示背景”类的按钮添加两个事件侦听器。单击任何一个时,将元素类更改为另一个。.show-background div{ display:block};.hide-background div{ display:none};const showBgnd = document.getElementsByClassName('show-background');const hideBgnd = document.getElementsByClassName('hide-background');showBgnd.addEventListener('click', (e)=>{&nbsp; showBgnd.setAttribute("class","hide-background");});hideBgnd.addEventListener('click', (e)=>{&nbsp; hideBgnd.setAttribute("class","show-background");});

桃花长相依

const descriptionBtn = document.querySelectorAll('.desc-btn');descriptionBtn.forEach(element => {&nbsp; element.onclick = function (e) {&nbsp; &nbsp; if (this.style.display === "block") {&nbsp; &nbsp; &nbsp; this.style.display = "none";&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; this.style.display = "block";&nbsp; &nbsp; }&nbsp; };});

梦里花落0921

您可以使用三级运算符来询问该框当前是否正在显示。如果是块将设置为隐藏,如果不是则将其设置为显示块。这是其他 JS 框架中常见的设计模式,因此值得一试。const descriptionBtn = document.querySelectorAll('.desc-btn');descriptionBtn.forEach((btn) => {&nbsp; btn.addEventListener('click', (e) => {&nbsp; &nbsp; descriptionBox = btn.nextElementSibling;&nbsp; &nbsp; descriptionBox.style.display === "block" ? discriptionBox.style.display = 'hidden' :&nbsp; &nbsp; &nbsp; discriptionBox.style.display = 'block'&nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript