我需要能够通过下拉菜单在同一页面上隐藏/显示多个div标签,但我希望他们使用jQuery'fadeToggle'。通过使用以下代码,我可以轻松地执行不带'fadeToggle':
function generateTask() {
document.getElementById('football').style.display = 'none';
document.getElementById('football2').style.display = 'none';
}
HTML:
<select name="something" id="something">
<option value="1" onclick="generateTask();">Football</option>
<option value="2" onclick="generateTask();">Cricket</option>
<option value="3" onclick="generateTask();">Baseball</option>
</select>
<div id="football">balls</div>
<div id="football2">shorts</div>
但这种解决方案并不优雅。任何帮助将不胜感激。
主要的复杂因素是板球标签“football”和“football2”可能都是板球所必需的,但只有“棒球2”才能说棒球。
答案 0 :(得分:1)
你可以试试这个
function generateTask(){ $('#football, #football2').toggle();}
或者你可以在每个应该受到下拉列表影响的元素上添加类: 例如:
<div id="football" class="football">balls</div>
<div id="football2" class="football cricket">shorts</div>
<div id="cricket" class="cricket">stick</div>
并定位与您的下拉操作链接的每个元素。
答案 1 :(得分:0)
如果你可以将选项的值保持为div的id,那么它将更加简单。 像这样的东西
标记
<select name="something" id="something">
<option value="football">Football</option>
<option value="cricket">Cricket</option>
<option value="baseball">Baseball</option>
</select>
<div id="football" class="content">Football content</div>
<div id="cricket" class="content">Cricket content</div>
<div id="baseball" class="content">Baseball content</div>
JS
$("#something").change(function(){
var id = "#"+this.value;
//This will hide all the divs with class content but not the selected option
$(".content").filter(":not("+id+")").hide();
$(id).fadeToggle();//This will toggle div based on the selected option
});