用于显示/隐藏页面上所有父/子div的JS代码

时间:2018-04-07 13:00:54

标签: javascript html css

我有一个简单的JS用于显示/隐藏DIV:

function HideShow(e, itm_id) {
var tbl = document.getElementById(itm_id);
if (tbl.style.display == ""){
    e.innerHTML = "<i class='fa fa-plus' aria-hidden='true'></i>";
    tbl.style.display = "none"; }
else {
    e.innerHTML = "<i class='fa fa-minus' aria-hidden='true'></i>";
    tbl.style.display = ""; }
}

这是Codepen上代码的一个工作示例:Show Hide Divs without jQuery

这是一个部分的示例:

<div id="activities" style="margin-bottom:50px;">
    <div style="color: #000; background: #eee; border-bottom:1px solid #ccc; padding:5px;">
        <h1 class="heading"><a href="javascript:;" onclick="HideShow(this,'parent_activities')"><i class='fa fa-minus' aria-hidden='true'></i></a> Activities <span style="color:#ccc;"></span></h1>
    </div>
        <div id="parent_activities" style="background: #fff; padding:20px;">
        <div id="activities__award-medal" style="background: #fff; padding-left:10px; background:#f1f1f1; border-top:1px solid #fff; font-size:30px;"><a href="javascript:;" onclick="HideShow(this,'child_award-medal')"><i class='fa fa-minus' aria-hidden='true'></i></a> award-medal <span style="color:#ccc;"></span></div>
        <div id="child_award-medal" style="background: #fff; padding:20px;">
            <ul class="gallery grid">
            <li>
                <a href="#">
                    <img title="military medal - ️" src="https://cdn.jsdelivr.net/emojione/assets/svg/1f396.svg" style="width:64x; height:64px" role="presentation">
                </a>
            </li>
            </ul>
        </div>
        <div id="activities__event" style="background: #fff; padding-left:10px; background:#f1f1f1; border-top:1px solid #fff; font-size:30px;"><a href="javascript:;" onclick="HideShow(this,'child_event')"><i class='fa fa-minus' aria-hidden='true'></i></a> event <span style="color:#ccc;"></span></div>
        <div id="child_event" style="background: #fff; padding:20px;">
            <ul class="gallery grid">
            <li>
                <a href="#">
                    <img title="jack-o-lantern - " src="https://cdn.jsdelivr.net/emojione/assets/svg/1f383.svg" style="width:64x; height:64px" role="presentation">
                </a>
            </li>
            </ul>
        </div>
    </div>
</div>

顶级示例的ID为parent_activities,然后有两个子值:

  1. child_award-medal
  2. child_event
  3. 我想弄清楚如何添加两个链接:

    1. 用于切换父母的HideShow功能的链接,以便显示/隐藏ID为parent_的所有div
    2. 用于切换子项的HideShow函数的链接,以便显示/隐藏ID为child_的所有div
    3. 我不确定我会怎么做。

      任何建议都非常感谢。感谢

4 个答案:

答案 0 :(得分:2)

注意: 这不是一个完全完整的解决方案。目的是帮助您处理暂停的部分。

  1. 尽量不要在您的HTML正文中嵌入JavaScript;这是不必要的标记,并且很难跟踪和调试错误。我没有更改您现有的电话,但通过使用addEventListener和更新的代码来演示如何完成此操作
  2. 您可以使用document.querySelectorAll定位元素,并查找您感兴趣的前缀(例如parent_child_)。要使用哪些前缀已添加到data-selector属性
  3. 中的链接
  4. 因为切换操作不会转到另一个页面,这些应该是按钮或跨度
  5. 要隐藏元素,可以使用Bootstrap显示类,因为我使用了d-none代表display none。 Bootstrap库提供了这些功能,使响应式布局变得更加容易
  6. 你的许多内联CSS应该在课堂上,这既可以减少你的标记,又可以使它更有条理
  7. // So forEach can be used on 'querySelectorAll' and 'getElementsByClassName' collections
    HTMLCollection.prototype.forEach = NodeList.prototype.forEach = Array.prototype.forEach;
    
    
    function HideShow(e, itm_id) {
      var tbl = document.getElementById(itm_id);
      if (tbl.style.display == "") {
        e.innerHTML = "<i class='fa fa-plus' aria-hidden='true'></i>";
        tbl.style.display = "none";
      } else {
        e.innerHTML = "<i class='fa fa-minus' aria-hidden='true'></i>";
        tbl.style.display = "";
      }
    }
    
    
    // -----------------------------------------------------------
    // NEW Code
    
    
    // New toggle links
    let toggles = document.getElementsByClassName('toggler');
    
    // Attach click event
    toggles.forEach(link => link.addEventListener('click', fnToggleElement))
    
    // Event handler definition
    function fnToggleElement() {
      let elements = document.querySelectorAll(`[id^="${this.dataset.selector}"]`)
      let className = 'd-none'
      elements.forEach(el => {
        let fas = el.parentElement.closest('.item,.sub-container,.menu-container').querySelectorAll('.fa')
        if (el.classList.contains(className)) {
          el.classList.remove(className)
          fas.forEach(fa => {
            fa.classList.remove('fa-plus')
            fa.classList.add('fa-minus')
          })
        } else {
          el.classList.add(className)
          fas.forEach(fa => {
            fa.classList.remove('fa-minus')
            fa.classList.add('fa-plus')
          })
        }
      })
    }
    .menu-container {
      margin-bottom: 50px;
    }
    
    .sub-container {
      padding: 20px;
    }
    
    .heading {
      color: #000;
      background: #eee;
      border-bottom: 1px solid #ccc;
      padding: 5px;
    }
    
    .indent {
      background: #fff;
      padding: 20px;
    }
    
    .icon {
      width: 64px;
      height: 64px;
    }
    
    .item {
      background: #fff;
      padding-left: 10px;
      background: #f1f1f1;
      border-top: 1px solid #fff;
      font-size: 30px;
    }
    
    .toggler {
      cursor: pointer;
      display: inline-block;
    }
    
    .gallery {
      width: 100%;
      *width: 99.94877049180327%;
      margin: 0;
      padding: 0;
    }
    
    .gallery.grid li {
      margin: 2px 5px;
    }
    
    .gallery.grid li {
      margin: 2px 5px;
      display: block;
    }
    
    .gallery.grid li:hover {
      background: #ccc;
    }
    
    .gallery.grid li {
      display: inline-block;
      border-top: 1px solid #eee;
      border-right: 1px solid #ccc;
      border-bottom: 1px solid #ccc;
      border-left: 1px solid #eee;
      padding: 6px;
      position: relative;
      -moz-box-sizing: border-box;
      border-radius: 3px 3px 3px 3px;
      background: #fff;
    }
    
    .gallery a {
      display: block;
    }
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
    
    <div class="container-fluid">
      <div class="row">
        <div class="col-sm"><span class="toggler btn-link" data-selector="parent_">Toggle Parents</span></div>
        <div class="col-sm"><span class="toggler btn-link" data-selector="child_">Toggle Children</span></div>
      </div>
    </div>
    
    <div class="container-fluid">
      <div id="activities" class="menu-container">
        <h1 class="heading">
          <a href="javascript:;" onclick="HideShow(this,'parent_activities')">
            <i class='fa fa-minus' aria-hidden='true'></i>
          </a> Activities
          <span style="color:#ccc;"></span>
        </h1>
        <div id="parent_activities" class="sub-container">
          <div id="activities__award-medal" class="item">
            <a href="javascript:;" onclick="HideShow(this,'child_award-medal')">
              <i class='fa fa-minus' aria-hidden='true'></i>
            </a> award-medal
            <span style="color:#ccc;"></span>
          </div>
          <div id="child_award-medal" class="indent">
            <ul class="gallery grid">
              <li>
                <a href="# ">
                  <img title="military medal - ️" src="https://cdn.jsdelivr.net/emojione/assets/svg/1f396.svg " class="icon" role="presentation">
                </a>
              </li>
            </ul>
          </div>
          <div id="activities__event " class="item">
            <a href="javascript:; " onclick="HideShow(this, 'child_event') ">
              <i class='fa fa-minus' aria-hidden='true'></i>
            </a> event
            <span style="color:#ccc; "></span>
          </div>
          <div id="child_event " class="indent">
            <ul class="gallery grid ">
              <li>
                <a href="# ">
                  <img title="jack-o-lantern - " src="https://cdn.jsdelivr.net/emojione/assets/svg/1f383.svg" class="icon" role="presentation">
                </a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    
      <div id="animals-nature" class="menu-container">
        <h1 class="heading"><a href="javascript:;" onclick="HideShow(this, 'parent_animals-nature')"><i class='fa fa-minus' aria-hidden='true'></i></a> Animals & Nature <span style="color:#ccc;"></span></h1>
        <div id="parent_animals-nature" class="sub-container">
    
          <div id="animals-nature__animal-amphibian " class="item ">
            <a href="javascript:;" onclick="HideShow(this, 'child_animal-amphibian')">
              <i class='fa fa-minus' aria-hidden='true'></i>
            </a> animal-amphibian
            <span style="color:#ccc;"></span>
          </div>
          <div id="child_animal-amphibian" class="indent">
            <ul class="gallery grid">
              <li>
                <a href="# ">
                  <img title="frog face -  " src="https://cdn.jsdelivr.net/emojione/assets/svg/1f438.svg " style="width:64x; height:64px " role="presentation ">
                </a>
              </li>
            </ul>
          </div>
    
          <div id="animals-nature__animal-bird " class="item">
            <a href="javascript:;" onclick="HideShow(this, 'child_animal-bird')">
              <i class='fa fa-minus' aria-hidden='true'></i>
            </a> animal-bird
            <span style="color:#ccc;"></span>
          </div>
          <div id="child_animal-bird" class="indent">
            <ul class="gallery grid">
              <li>
                <a href="# ">
                  <img title="turkey -  " src="https://cdn.jsdelivr.net/emojione/assets/svg/1f983.svg " style="width:64x; height:64px " role="presentation ">
                </a>
              </li>
            </ul>
          </div>
        </div>
      </div>

答案 1 :(得分:1)

尝试以下选择器并应用:

document.querySelectorAll('[id^="child_"]')

请参阅以下代码段中的示例:

function toggleIdStartingWith( prefix = 'parent_' ){
  
  // Select all IDs starting with prefix and turn this NodeList into an array 
  // so we can loop through it easily later.
  var all = [...document.querySelectorAll(`[id^="${prefix}"]`)];
  
  // Determine whether we want to turn them on or off by
  // checking the first element. You might want to also check
  // if any elements are found at all before doing this.
  var hidden = all[ 0 ].style.display === 'none';
  
  // Apply the display style to all.
  all.forEach(element => {
    
    element.style.display = hidden ? '' : 'none';
    
  });
  
  // Return the inverted hidden value, which is what we applied.
  // Useful if you want to toggle stuff, and then see what the result
  // was in the code that called the function.
  return !hidden;
  
}

// For testing purposes I am hooking two buttons up for testing this.

document.getElementById('hideshow_parents').addEventListener( 'click', event => {
  
  event.preventDefault()
  event.target.textContent = toggleIdStartingWith( 'parent_' )
    ? 'Show all Parents'
    : 'Hide all Parents'
  
})
document.getElementById('hideshow_children').addEventListener( 'click', event => {
  
  event.preventDefault()
  event.target.textContent = toggleIdStartingWith( 'child_' )
    ? 'Show all Children'
    : 'Hide all Children'
    
})
<div id="parent_1">Parent</div>
<div id="child_1">Child</div>
<div id="parent_2">Parent</div>
<div id="child_2">Child</div>
<div id="parent_3">Parent</div>
<div id="child_3">Child</div>
<div id="parent_4">Parent</div>
<div id="child_4">Child</div>
<div id="parent_5">Parent</div>
<div id="child_5">Child</div>

<button id="hideshow_parents">Hide/Show Parents</button>
<button id="hideshow_children">Hide/Show Children</button>

正如您在评论中所提到的,根据切换状态切换类也很容易。我个人认为你不应该混合html和交互性,所以我将在我的例子中使用addEventListener

function toggleIdStartingWith( prefix = 'parent_' ){
  
  var all = [...document.querySelectorAll(`[id^="${prefix}"]`)];
  var hidden = all[ 0 ].style.display === 'none';
  
  all.forEach(element => {
    
    element.style.display = hidden ? '' : 'none';
    
  });
  
  return !hidden;
  
}

document.querySelector('h1').addEventListener( 'click', event => {
  
  event.preventDefault()
  
  if( toggleIdStartingWith( 'parent_' ) ){
    
    event.target.textContent = 'Show';
    event.target.classList.remove( 'fa-minus' )
    event.target.classList.add( 'fa-plus' )
    
  } else {
    
    event.target.textContent = 'Hide';
    event.target.classList.add( 'fa-minus' )
    event.target.classList.remove( 'fa-plus' )
    
  }
  
})
.fa-minus:before { content: '-'; }
.fa-plus:before { content: '+'; }
<div id="parent_1">Parent</div>
<div id="parent_2">Parent</div>
<div id="parent_3">Parent</div>
<div id="parent_4">Parent</div>
<div id="parent_5">Parent</div>

<h1 class="fa-minus">Hide</h1>

如果您坚持在html中将其作为onclick,请将其包装在函数中:

function toggle( target, prefix ){

  if( toggleIdStartingWith( prefix ) ){

    target.textContent = 'Show';
    target.classList.remove( 'fa-minus' )
    target.classList.add( 'fa-plus' )

  } else {

    target.textContent = 'Hide';
    target.classList.add( 'fa-minus' )
    target.classList.remove( 'fa-plus' )

  }

}

并称之为:

<h1 onclick="toggle( this, 'parent_); return false;'"></h1>

另外,您知道,如果您要在HTML中使用return false处理程序来防止发生默认事件,那么onclick可能会有所帮助。然后,您可以将链接设置为#,而不是丑陋的javascript:;

答案 2 :(得分:0)

您应该使用querySelectorAll()选择以#&#34;开头的&#34; ID。这可以像document.querySelectorAll('[id^="start_"]')一样完成,然后遍历应用样式隐藏或显示的元素。

看看这个小提琴:https://jsfiddle.net/1c38dezk/

答案 3 :(得分:0)

您应该使用querySelectorAll()来选择以#&#34;开头的&#34; ID。 祝你有愉快的一天