根据下拉选择显示多个div

时间:2016-07-06 07:23:21

标签: javascript jquery html

具有特定数量的div(每次不同)的html文件是无关紧要的。为简单起见:

<div id="plate1">
  <p>plate 1 info</p>
</div>
<div id="plate2">
  <p>plate 2 info</p>
</div>
<div id="plate3">
  <p>plate 3 info</p>
</div>
<div id="plate2">
  <p>plate 2 additional info</p>
</div>

我想知道动态填充下拉列表<select multiple></select>的可能性(基于唯一块的ID):

enter image description here

仅显示选中的那些div:

plate2 info
plate3 info
plate 2 additional info

2 个答案:

答案 0 :(得分:1)

尝试这样的事情。

只需循环显示:selected的所有选项,并显示div依赖于他们text()val()

&#13;
&#13;
$("#myselect option").prop("selected",true);

$("#myselect").change(function(){
  $(".mydiv").hide();
  $("#myselect option:selected").each(function(){
    $("#mydiv"+$(this).val()).show();
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="myselect">
  <option value="1">div1</option>
  <option value="2">div2</option>
  <option value="3">div3</option>
  <option value="4">div4</option>
</select>

<div class="mydiv" id="mydiv1">First div</div>
<div class="mydiv" id="mydiv2">Second div</div>
<div class="mydiv" id="mydiv3">third div</div>
<div class="mydiv" id="mydiv4">Fourth div</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

  • 创建一个对象并将其指定为元素的id,将其值设置为true
  • 如果在id中迭代了具有相同Array#filter的其他元素,则会对其进行过滤
  • Array#map已过滤的数组并将display设置为已过滤元素的block
  • 同时创建具有option属性
  • selected个元素
  • 通过change元素
  • 附加select个事件
  • 如果option的值为selected,则div idvaluedisplay : none

&#13;
&#13;
var select = document.getElementById('select');
var elems = document.querySelectorAll('.plate');
var obj = {};
var filtered = [].filter.call(elems, function(el) {
  if (!obj[el.id]) {
    obj[el.id] = true;
    return true;
  } else {
    return false;
  }
});
var selectOpt = filtered.map(function(el) {
  el.style.display = 'block';
  return '<option selected>' + el.id + '</option>';
});
select.innerHTML = selectOpt.join('');
select.addEventListener('change', function() {
  for (var i = 0, iLen = select.options.length; i < iLen; i++) {
    var opt = select.options[i];
    var val = opt.value || opt.text;
    if (opt.selected) {
      document.getElementById(val).style.display = 'block';
    } else {
      document.getElementById(val).style.display = 'none';
    }
  }
});
&#13;
div {
  display: none;
}
&#13;
<div id="plate1" class="plate">
  <p>plate 1 info</p>
</div>
<div id="plate2" class="plate">
  <p>plate 2 info</p>
</div>
<div id="plate3" class="plate">
  <p>plate 3 info</p>
</div>
<div id="plate2" class="plate">
  <p>plate 2 additional info</p>
</div>

<select multiple id='select'></select>
&#13;
&#13;
&#13;