Need to replace +/- characters with html codes (for example) — in small piece of jQuery

大憨熊 提交于 2019-12-11 18:17:52

问题


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') ? '-' : '+');
    }); 
});


来源:https://stackoverflow.com/questions/5654838/need-to-replace-characters-with-html-codes-for-example-8212-in-small-pi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!