在功能中对变量进行分组 - 第2部分

时间:2017-07-30 14:25:03

标签: javascript

我昨天问了一个关于grouping vars的问题,我得到了答案,但它只解决了我的一半问题:

我希望能够在javascript中对变量进行分组,这样我就可以选择要显示的一组div和要隐藏的组。从上一个问题我现在有:

var elemsById = ['myDIVA','myDIVB','myDIVC'].map(id=>[id,document.getElementById(id)]);
    
function showThisAndHideRest(showId){
  elemsById.forEach(function([id,el]){
    el.style.display=id===showId?'block':'none';
  });
}
<div id="myDIVA" style="display:none;">blabla 1</div>
<div id="myDIVB" style="display:none;">blabla 2</div>
<div id="myDIVC" style="display:none;">blabla 3</div>
<div onClick="showThisAndHideRest('myDIVB');">Show NEW VERSION</div>

这适用于显示一个div并隐藏所有其他div。但我无法选择一组显示的div。 这是我希望一些友好的专家可以铺平道路的地方:-) 谢谢你的期待。 注意:我有很多包含文本和css风格的div(40+和不断增长) - 我想将它们分组以在页面上以各种组合显示而无需重新加载页面。跨浏览器兼容性(包括略微较旧的IE)将更可取: - )

2 个答案:

答案 0 :(得分:1)

假设showId是一个数组

function showThisAndHideRest(showId){
  elemsById.forEach(function([id,el]){
    el.style.display=showId.includes(id)?'block':'none';
  });
}

如果id在数组中,则Array.includes返回true。

你现在应该能够做到

showThisAndHideRest(["elem1","elem2"])

答案 1 :(得分:1)

如果您不介意稍微重构一下代码:

// find all elements with the class 'list-item'
// and convert the result to an array 
const divs = [...document.querySelectorAll('.list-item')];

function showIndices (indices) {
  // loop over the <div>s
  divs.forEach((div, index) => {
    // if the array contains the <div>'s index 
    if (indices.indexOf(index) !== -1) {
      // make the <div> visible
      div.classList.add('visible');
    } else {
      // hide the <div>
      div.classList.remove('visible');
    }
  });
}

const select = document.querySelector('select'); // the <select> element
select.addEventListener('change', function () {
  // this function is executed whenever the value of the <select> element changes
  if (this.selectedIndex === 0) {
    // the user selected the first <option>
    showIndices([0, 4, 5]); // show A, E, F
  } else if (this.selectedIndex === 1) {
    // the user selected the second <option>
    showIndices([1, 2, 3, 8]); // show B, C, D, I
  } 
});
.list-item {
  display: none;
}

.list-item.visible {
  display: block;
}
<div class="list-item">A</div>
<div class="list-item">B</div>
<div class="list-item">C</div>
<div class="list-item">D</div>
<div class="list-item">E</div>
<div class="list-item">F</div>
<div class="list-item">G</div>
<div class="list-item">H</div>
<div class="list-item">I</div>

<!-- ... -->

Select what divs to show:

<select>
  <option>A, E, F</option>
  <option>B, C, D, I</option>
</select>

当然,您不需要使用<select>元素。只需使用您希望显示的索引数组调用showIndices(...)