我有这个列表:
<ul class="filters">
<li id="all">All</li>
<li id="cat1">Cat1</li>
<li id="cat2">cat2</li>
<li id="cat3">cat3</li>
</ul>
<div class="col s12 m4 l3 category-cat1">
<div class="card-panel grey lighten-5 z-depth-1">
<div class="row">
<div class="col s4">
<img src="/static/images/cat124.jpg" alt="" class="circle responsive-img">
</div>
<div class="col s8">
<span class="black-text">
This is a square image. Add the "circle" class to it to make it appear circular.
</span>
</div>
</div>
<a href="/">View Details</a>
</div>
</div>
....
....
页面末尾的 JS 代码:
$('.filters li').click(function () {
$('[class^=category-]').hide('fast','linear');
var id = $(this).attr('id');
if(id == 'all') {
$('[class^=category-]').show('fast','linear');
} else {
$('.category-'+id).show('fast','linear');
}
});
我尝试通过过滤器显示和隐藏具有相同类别的div。我以为这很容易,但是当我点击<li>
时什么都没发生。控制台上既没有错误,也没有 div 发生变化。
最佳答案
问题在于选择器^=
,即attribute starts with selector ,您的类名属性值不以 category-
开头,这就是它不起作用的原因。
尝试属性包含选择器
$('[class*=category-]').hide('fast','linear');
但正确的解决方案可能是向那些 div
元素添加一个类,例如 category
<div class="col s12 m4 l3 category-cat1 category">
</div>
然后使用它
$('div.category').hide('fast','linear');
关于javascript - 单击列表元素时显示和隐藏 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28538812/