Need to replace +/- characters with html codes (fo

2019-08-27 12:54发布

问题:

I have a fairly mundane piece jQuery that toggles a div's visibility when a + is clicked and hides it when a - is clicked (the + changes to a - when clicked). The problem is that the +/- toggler follows some text that sometimes has a + or - in it and both toggle. For instance: Find out more about blah-blah +. When clicked, the plus changes to a minus. When clicked again, both minuses change to pluses.

I thought if i just changed the + to a + and a minus to a — in the jquery it would solve the problem, but it doesn't work. The div visibility toggles on/off but the plus/minus symbols don't change.

Here is the script:

function toggleSpecial(element)
{
    jQuery(element).next(".hidden").slideToggle("fast"); 
    jQuery(element).html(function(i,html) {
        if (html.indexOf('+') != -1 ){
           html = html.replace('+','-');
        } else {
           html = html.replace('-','+');
        }
        return html;
    });
}

Here is the script with HTML codes replacing the + and - which doesn't work.

function toggleSpecial(element)
{
    jQuery(element).next(".hidden").slideToggle("fast"); 
    jQuery(element).html(function(i,html) {
        if (html.indexOf('+') != -1 ){
           html = html.replace('+','—');
        } else {
           html = html.replace('—','+');
        }
        return html;
    });
}

Any ideas about what I am doing wrong or suggestions? Thanks!

回答1:

You're basing your visibility toggling off of something totally arbitrary. Why not just see if it's visible or not? Additionally, you can just wrap the character in a span and then do something like this:

$('#iamelement').click(function() {
    var $this = $(this);
    $this.next(".hidden").slideToggle("fast", function() {
        $this.find('span').text($(this).is(':visible') ? '-' : '+');
    }); 
});

This would be for something like this:

<a href="#" id="iamelement">toggle thing <span>+</span></a>
<div class="hidden">
    thing
</div>

The proof is in the fiddle: http://jsfiddle.net/rFeeJ/1/

ADDITIONS: To make it generic, you need to use classes instead of IDs. I was merely trying to be illustrative.

<a href="#" class="toggler">toggle thing <span>+</span></a>
<div class="hidden">
    thing
</div>
<a href="#" class="toggler">toggle thing 2 <span>+</span></a>
<div class="hidden">
    thing 2 
</div>
<a href="#" class="toggler">toggle thing 3 <span>+</span></a>
<div class="hidden">
    thing 3
</div>

$('a.toggler').click(function() {
    var $this = $(this);
    $this.next(".hidden").slideToggle("fast", function() {
        $this.find('span').text($(this).is(':visible') ? '-' : '+');
    }); 
});


标签: jquery toggle