简体   繁体   中英

How can I toggle plus and minus icons with jQuery?

I want to toggle the guide-content div and change the + icon to - icon and again - to + icon. To do this I have this jQuery and HTML:

 $(document).ready(function() { $(".collapse").click(function() { $(this).parents().next(".guide-content").toggle(); $(this).text("+"); }, function() { $(this).text("-"); $(this).parents().next(".guide-content").toggle(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="guide-collapse"> <div class="guide-title"> <h2>アンティーク着物について <span class="collapse">+</span></h2> </div> <div class="guide-content"> </div> </div> <div class="guide-collapse"> <div class="guide-title"> <h2>アンティーク着物について <span class="collapse">+</span></h2> </div> <div class="guide-content"> </div> </div>

But it's not changing the icon from + to - and - to +.

I would use CSS to toggle it based on a class.

This will allow you to use an icon for more detail and flexibility.

$('body').on('click', '.collapse', function(event) {
    $(this).toggleClass('isActive');
});

If you want a toggle behaviour, change you JS code to the following:

$(document).ready(function() {
    $(".collapse").click(function() {
        $(this).parents().next(".guide-content").toggle();
        if($(this).text() == "+"){
            $(this).text("-");
        }
        else {
          $(this).text("+");
        }
        
    });
});

This will change the text to "+" if it is "-" and "-" if it is "+", each time you click.

I'm not entirely sure of your intent, but one strategy is to just use two elements with one hidden and toggle both:

 $(document).ready(function() { $(".guide-collapse").click(function() { $(this).find('h2 span').toggle(); $(this).find('.guide-content').slideToggle(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="guide-collapse"> <div class="guide-title"> <h2>アンティーク着物について <span class="collapse">+</span><span class="collapse" style="display: none;">-</span></h2> </div> <div class="guide-content" style="display: none;">Guide content here.</div> </div> <div class="guide-collapse"> <div class="guide-title"> <h2>アンティーク着物について <span class="collapse">+</span><span class="collapse" style="display: none;">-</span></h2> </div> <div class="guide-content" style="display: none;">Guide content here.</div> </div>

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