具有特定数量的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):
仅显示选中的那些div:
plate2 info
plate3 info
plate 2 additional info
答案 0 :(得分:1)
尝试这样的事情。
只需循环显示:selected
的所有选项,并显示div依赖于他们text()
或val()
$("#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;
答案 1 :(得分:1)
id
,将其值设置为true
id
中迭代了具有相同Array#filter
的其他元素,则会对其进行过滤Array#map
已过滤的数组并将display
设置为已过滤元素的block
option
属性selected
个元素
change
元素select
个事件
option
的值为selected
,则div
id
为value
,display : none
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;