简体   繁体   中英

Jquery toggle span text in trigger

I'm so close to figuring this out, i think. I'm new to javascript, but here's my situation.

I've got some lists hidden by default. Clicking on the headers displays the lists. I want the span in the header to change from '+' to '-' to hide and show respectively.

The problem i'm running into is the span changes for both headers, instead of just the one being clicked.

    <div>
    <h3 class = "trigger"><span>+</span>Heading 1</h3>
    <ul class = "toggle">
        <li>Line One</li>
        <li>Line Two</li>
        <li>Line Three</li>
    </ul>
</div>
<div>
    <h3 class = "trigger"><span>+</span>Heading 2</h3>
    <ul class = "toggle">
        <li>Line One</li>
        <li>Line Two</li>
        <li>Line Three</li>
    </ul>
</div>

And here is the accompanying javascript for it.

$(".trigger").click(function(){
    $(this).next(".toggle").slideToggle(function(){
    $('span').text(
        $('.toggle').is(':visible') ? '-' : '+');
    });
});

Here is a jsfiddle

Try this:

$(".trigger").click(function(){
    var trigger = $(this);
    $(this).next(".toggle").slideToggle(function(){
    trigger.children('span').text(
        $('.toggle').is(':visible') ? '-' : '+');
    });
});

You need to specifically tell javascript to only hide span related to that header

http://jsfiddle.net/sWvbq/5/

One way of doing that :)

$(".trigger").click(function(){
    var _that = $(this); // remember parent
    $(this).next(".toggle").slideToggle(function(){
    _that.find('span').text( // only toggle span related to parent
        $('.toggle').is(':visible') ? '-' : '+');
    });
});

Try:

$(".trigger").click(function(){
    var $this = $(this);
    $this.next(".toggle").slideToggle(function(){
        $this.find("span").text($(this).is(':visible') ? '-': '+');
    });
});

Demo: http://jsfiddle.net/N8YVD/

you were pretty close :) Here is the update jsfiddle (there are multiple approaches to reach it). If you access $('span') inside slideToggle you will acccess all spans thats why it changes both. You need to access only the span from clicked heading so you will have to traverse back to it.

$(".trigger").click(function(){
    $(this).next(".toggle").slideToggle(function(){
    $(this).prev().children('span').text(
        $('.toggle').is(':visible') ? '-' : '+');
    });
});

In jQuery when you use the . operator you are asking jQuery to get all of the DOM elements with a CLASS of toggle. If you want one to change, you can ask for a specific id. Name them uniquely, and access with $('#IDHERE') and you will get one to update and the other will stay the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM