I have a hidden div and a link to toggle the div's visibility. The link contains text/html that needs to also toggle ('hide'/'show'). Here is my function:

jQuery('#toggle_filter_link').click(function() {
    jQuery('#searchfilter_wrap').slideToggle("slow");
    jQuery(this).html(jQuery(this).text() == 'Hide ↑' ? 'Show ↓' : 'Hide ↑');
});

This function works as intended until I add the arrows to the HTML (↑ and ↓), at which point it toggles to "Hide ↑" the first time, and then remains stuck.

Here a jsFiddle.

I assume that I need to escape the HTML Entities somehow, but considering that the first switch works I am a bit confused. It's probably something obvious that I'm missing though. :-)

Thanks for the help!

有帮助吗?

解决方案

You're comparing text to html

Change jQuery(this).text() to jQuery(this).html().

Note that you might still have issues due to the way that browsers normalise HTML and you would probably be better off testing some other condition.

jQuery('#toggle_filter_link').click(function() {
    jQuery('#searchfilter_wrap').slideToggle("slow");
    var $this = jQuery(this);
    if ($this.hasClass('show')) {
        $this.removeClass('show');
        $this.html('Hide ↑');
    } else {
        $this.addClass('show');
        $this.html('Show ↓');
    }
});

… or just testing for something that isn't going to be normalised:

jQuery('#toggle_filter_link').click(function() {
    jQuery('#searchfilter_wrap').slideToggle("slow");
    jQuery(this).html(jQuery(this).text().indexOf('Hide') > -1 ? 'Show ↓' : 'Hide ↑');
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top