JQuery:切换单击的元素并隐藏所有其他元素 [英] JQuery: Toggle Element that is clicked and hide all other
问题描述
我想隐藏任何可见的span元素(如果有的话),如果单击某个元素,则再次切换它
I want to hide any visible span elements if any is visible, and toggle it again if a element is clicked
<div class="item">
<a href="">element1</a> <span>span1</span>
<br>
</div>
<div class="item">
<a href="">element2</a> <span>span2</span>
<br>
</div>
<div class="item">
<a href="">element3</a> <span>span3</span>
<br>
</div>
<div class="item">
<a href="">element4</a> <span>span4</span>
<br>
</div>
JS
JS
$('.item span').hide();
var all_spans = $('.item a').parent().find('span');
$('.item a').click(function(e) {
e.preventDefault();
// hide all span
all_spans.hide();
$this = $(this).parent().find('span');
// here is what I want to do
if ($this.is(':hidden')) {
$(this).parent().find('span').show();
} else {
$(this).parent().find('span').hide();
}
});
问题是当我点击例如'元素1
'' span1
'仍然可见,我想切换此
the issue is when I click for example 'element 1
' 'span1
' is still visible and I want to toggle this
推荐答案
$('.item span').hide();
$('.item a').click(function(e){
e.preventDefault();
// hide all span
var $this = $(this).parent().find('span');
$(".item span").not($this).hide();
// here is what I want to do
$this.toggle();
});
检查演示
更新说明:
问题在于你什么时候隐藏所有跨度,您还隐藏当前跨度=>所有跨度具有相同的状态(隐藏),然后您的下一行再次显示它。隐藏时必须排除当前元素,并使用toggle方法切换其状态(比使用if检查更简单)
The problem is when you hide all spans, you also hide the current span => all spans have the same state (hidden), and your next line display it again. You have to exclude the current element when hiding and use toggle method to toggle its state (simpler than using if to check)
另一个问题是尝试通过使用避免隐式全局 var
申报 $ this
:
Another problem is try to avoid implicit global by using var
to declare $this
:
var $this = $(this).parent().find('span');
这篇关于JQuery:切换单击的元素并隐藏所有其他元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!