Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

javascript - JQuery: Toggle Element that is clicked and hide all other

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

$('.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();
    }

});

live example http://jsfiddle.net/BGSyS/

the issue is when I click for example 'element 1' 'span1' is still visible and I want to toggle this

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
 $('.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();

});

Check demo

Update with explanation:

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)

Another problem is try to avoid implicit global by using var to declare $this:

var $this = $(this).parent().find('span');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...