繁体   English   中英

如何在 JavaScript 中使用一堆按钮(显示/隐藏)

[英]How to work with a bunch of buttons (Show/Hide) in JavaScript

我想了解如何在不为以下任务指定 ID 的情况下使用一组按钮:

隐藏和显示 Div 主体,Div header 保持显示。

我可以用这段代码制作一个:

function hide(){
document.getElementById('here').classList.toggle('hide')
}

但事实证明,单独隐藏/显示每个都更加困难。

此处的示例:显示/隐藏 div 正文

我知道有类似的东西:

Let btns = document.querySelectorAll('buttons);
Let tables = document.getElementsByClassName('here');

function HideShow(){
//What do I put here???????  :)
}

注意:我不能使用 id,因为我想添加这么多 div 以使其动态化。

更新::::::更新::::::更新:::::: 我必须以老式方式进行操作,使用 ids,: 和 IF/ELSE,不酷! :(

let tables = document.getElementsByClassName('here');

var theParent = document.querySelector('#theDude');
theParent.addEventListener('click', doSomeThing, false);

function doSomeThing(e){
if( e.target!==e.currentTarget){
var clickedItem = e.target.id;

if(clickedItem=='one'){
tables[0].classList.toggle('hide')
}else if(clickedItem=='two'){
tables[1].classList.toggle('hide')
}else if(clickedItem=='three'){
tables[2].classList.toggle('hide')
}else if(clickedItem=='four'){
tables[3].classList.toggle('hide')
}
e.stopPropagation();
}
}

将您的节点列表传递到您的隐藏和显示中,然后对其进行迭代

Let btns = document.querySelectorAll('buttons);
Let tables = document.getElementsByClassName('here');

function HideShow(elemArray){ // note: I've added an elemArray parameter here
//What do I put here???????  :)
  elemArray.forEach(elemArray, function(elem) {
    //with each element, toggle hide or show
    //elem.classList...
  }
}

HTML: <button onclick="hideThisButton(this);">Button</button>

JS:让 btns = document.querySelectorAll('buttons); let tables = document.getElementsByClassName('here');

// use this to hide all the buttons
function HideShow(){
 for(let i=0;i<btns.length;i++){
     // you can access the index i over here
     // change the logic to hide or show specific buttons
     btns[i].classList.toggle('hide');
  }
}

   // use this method for hiding a specific button on click
   function hideThisButton(event)
   {
    var btn = event.target;
    btn.classList.toggle('hide');
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM