我知道这很容易做到,我确信我错过了一些明显的东西,但我希望使用jQuery切换来隐藏/显示4个不同的div。
我有一个小提琴:http://jsfiddle.net/4SDesignStudio/agjqj80t/
我错过了什么?
HTML:
<ul class="wine-filters">
<li style="float:left; margin-right:1.5em;">Filters:</li>
<li class="button-row red-filter">Reds</li>
<li class="button-row white-filter">Whites</li>
<li class="button-row sparkling-filter">Sparkling</li>
<li class="button-row dessert-filter">Dessert</li>
</ul>
<div class="red-wine">
** A bunch of <article> sections with each red wine **
</div>
<div class="white-wine">
** A bunch of <article> sections with each white wine **
</div>
<div class="sparkling-wine">
** A bunch of <article> sections with each sparkling wine **
</div>
<div class="dessert-wine">
** A bunch of <article> sections with each dessert wine **
</div>
jQuery的:
var $redFilter = $('red-filter');
var $whiteFilter = $('white-filter');
var $sparklingFilter = $('sparkling-filter');
var $dessertFilter = $('dessert-filter');
var $redWine = $('.red-wine');
var $whiteWine = $('.white-wine');
var $sparklingWine = $('.sparkling-wine');
var $dessertWine = $('.dessert-wine');
// Event handlers - Wine Filters
$redFilter.on('click', function(event) {
$redWine.toggle('show');
$whiteWine.toggle('hide');
$sparklingWine.toggle('hide');
$dessertWine.toggle('hide');
});
$whiteFilter.on('click', function(event) {
$redWine.toggle('hide');
$whiteWine.toggle('show');
$sparklingWine.toggle('hide');
$dessertWine.toggle('hide');
});
$sparklingFilter.on('click', function(event) {
$redWine.toggle('hide');
$whiteWine.toggle('hide');
$sparklingWine.toggle('show');
$dessertWine.toggle('hide');
});
$dessertFilter.on('click', function(event) {
$redWine.toggle('hide');
$whiteWine.toggle('hide');
$sparklingWine.toggle('hide');
$dessertWine.toggle('show');
});
答案 0 :(得分:4)
正如我上面评论的,有两个问题:
var $redFilter = $('red-filter');
应为var $redFilter = $('.red-filter');
。.toggle()
不接受显示/隐藏字符串,但它接受true / false布尔值。但是,如果您只是向列表项添加数据属性(例如),则可以将jQuery减少为:
$('.button-row').click(function () {
$('ul ~ div').hide();
$('.' + $(this).data('type')).show()
})
<强> jsFiddle example 强>
答案 1 :(得分:1)
我认为您使用的是.toggle()
错误。切换将隐藏/显示元素,具体取决于是否显示/隐藏。既然您已经知道要通过切换完成什么,为什么不这样做:
$redFilter.on('click', function(event) {
$redWine.show();
$whiteWine.hide();
$sparklingWine.hide();
$dessertWine.hide();
});
由于.toggle('hide');
不应(?)工作。
另外,根据评论:
var $redFilter = $('.red-filter');
var $whiteFilter = $('.white-filter');
var $sparklingFilter = $('.sparkling-filter');
var $dessertFilter = $('.dessert-filter');
在前4个变量上缺少.
选择器。
答案 2 :(得分:0)
这四行中的选择器缺失&#39;。&#39;
var $redFilter = $('red-filter');
var $whiteFilter = $('white-filter');
var $sparklingFilter = $('sparkling-filter');
var $dessertFilter = $('dessert-filter');
添加句点,例如.red-filter
以修复。