我使用 Select 隐藏和显示多个 div。当我显示 div 时,我也会显示它的关联标题。除了一件事之外,这一切都运行良好:
当我选择“显示全部”时,我想显示内容 div,但不显示标题。所以基本上我希望显示回到开始时的状态。只有内容项,没有标题。当您选择特定项目时,该项目必须显示其标题(就像当前一样),但是当您想要查看所有项目时,则必须显示内容项目,但不显示标题。
我尝试创建一个 fiddle ,但收到错误“(index):74 Uncaught TypeError: Illegal constructoronchange @ (index):74”。它对我来说工作得很好,但我无法让它在 fiddle 中工作。
<script type="text/javascript">
/*<![CDATA[*/
function Selection(sel,cls){
var objs=bycls(cls),z0=0;
for (;z0<objs.length;z0++){
objs[z0].style.display=objs[z0].className.indexOf(sel.value)>-1||sel.value=='ShowAll'?'block':'none';
}
}
function bycls(nme){
for (var reg=new RegExp('\\b'+nme+'\\b'),els=document.getElementsByTagName('DIV'),ary=[],z0=0; z0<els.length;z0++){
if(reg.test(els[z0].className)){
ary.push(els[z0]);
}
}
return ary;
}
/*]]>*/
</script>
<div>
<form class="form-inline">
<label for="show">Show</label>
<select name="type" onchange="Selection(this,'Selection');" class="form-control" style="width: 150px;" id="show">
<option value="ShowAll">Show All</option>
<option value="Selection2">Only 2</option>
<option value="Selection3">Only 3</option>
<option value="Selection4">Only 4</option>
<option value="Selection5">Only 5</option>
</select>
</form>
</div>
<!--- HEADING FOR DIV 2 --->
<div class="Selection Selection2" style="display: none;">
<h2>Heading 2</h2>
</div>
<!--- HEADING FOR DIV 3 --->
<div class="Selection Selection3" style="display: none;">
<h2>Heading 3</h2>
</div>
<!--- HEADING FOR DIV 4 --->
<div class="Selection Selection4" style="display: none;">
<h2>Heading 4</h2>
</div>
<!--- HEADING FOR DIV 5 --->
<div class="Selection Selection5" style="display: none;">
<h2>Heading 5</h2>
</div>
<!--- CONTENT FOR DIV 2 --->
<div class="Selection Selection2">
<p>Content for 2</p>
</div>
<!--- CONTENT FOR DIV 3 --->
<div class="Selection Selection3">
<p>Content for 3</p>
</div>
<!--- CONTENT FOR DIV 4 --->
<div class="Selection Selection4">
<p>Content for 4</p>
</div>
<!--- CONTENT FOR DIV 5 --->
<div class="Selection Selection5">
<p>Content for 5</p>
</div>
最佳答案
$('#show').on('change', function(){
var val = $(':selected',this).attr('value');
if (val === 'ShowAll') {
$('.Selection').show()
$('.Selection').has('h2').hide();
} else {
$('.Selection').hide()
$('.'+val).show()
}
})
感谢 DaniP 提供的解决方案。 在这里 fiddle :https://jsfiddle.net/cxj9yj8p/
关于javascript - 使用 JQuery 隐藏和显示多个 div 以及隐藏标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384428/