遇到一些 jQuery 问题,因为我对它相当陌生,我有一些 jQuery 代码隐藏了 <li>
的过滤器菜单项目。但是,当我使用它时,它还会隐藏 <li>
我在主菜单标题中使用的标签。
我正在考虑为 <li>
指定一个特定的类名被隐藏,但他们已经在使用特定的名称。 (例如,会计、 express 等)
我怎样才能只隐藏特定的 <li>
标签而不是主菜单标题中的标签?
我可以为 <li>
分配不同的标识符吗?我想躲起来吗?
要隐藏的 li 的 HTML 代码:
<div class="tags">
<div id="col">
<label>
<input type="checkbox" rel="accounting" />Accounting</label>
</div>
<div id="col">
<label>
<input type="checkbox" rel="courier" />Courier</label>
</div>
<div id="col">
<label>
<input type="checkbox" rel="project-management" />Project Management</label>
</div>
<div id="col">
<label>
<input type="checkbox" rel="video-games" />Video Games</label>
</div>
</div>
<ul class="results">
<li class="accounting" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Accounting</a>
</li>
<li class="courier" style="list-style-type:none"><a href="{{ path('job1') }}" style="text-decoration: none">Courier / Parcel Delivery</a>
</li>
<li class="project-management" style="list-style-type:none"><a href="{{ path('job3') }}" style="text-decoration: none">Game QA Project Management</a>
</li>
<li class="video-games" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Video Games</a>
</li>
</ul>
jQuery 代码(隐藏所有 li 标签)
<script>
$('div.tags').find('input:checkbox').on('click', function () {
var vals = $('input:checkbox:checked').map(function () {
return $(this).attr('rel');
}).get();
$('li').hide().filter(function () {
return ($.inArray($(this).attr('class'), vals) > -1)
}).show()
if ($('input:checkbox:checked').length == 0) $('li').show()
});
</script>
最佳答案
尝试改进选择器使其更具体,如下所示:
<script>
$('div.tags').find('input:checkbox').on('click', function () {
var vals = $('input:checkbox:checked').map(function () {
return $(this).attr('rel');
}).get();
$('.results li').hide().filter(function () {
return ($.inArray($(this).attr('class'), vals) > -1)
}).show()
if ($('input:checkbox:checked').length == 0) $('.results li').show()
});
</script>
从 $('li')
到 $('.results li')
的变化将导致它只选择 ul< 中的列表元素
与 results
类。
关于jQuery 隐藏了所有的 <li> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27725842/