admin管理员组

文章数量:1410712

I have a + icon and a - icon. When someone clicks the + icon a box appears and the icon changes to a - icon. If they click again the box disappears and the icon changes to a + icon.

Here is the code I tried but its not working...

$("#box").toggle(function(e){
        $("#icon").attr ("src","/images/icon_expand.png")
    },
    function(e) { 
        $("#icon").attr("src","/images/icon_retract.png")
    }
);

Any ideas?

Thank you!

I have a + icon and a - icon. When someone clicks the + icon a box appears and the icon changes to a - icon. If they click again the box disappears and the icon changes to a + icon.

Here is the code I tried but its not working...

$("#box").toggle(function(e){
        $("#icon").attr ("src","/images/icon_expand.png")
    },
    function(e) { 
        $("#icon").attr("src","/images/icon_retract.png")
    }
);

Any ideas?

Thank you!

Share Improve this question edited Nov 24, 2010 at 10:31 Jan Hančič 53.9k17 gold badges98 silver badges101 bronze badges asked Nov 24, 2010 at 10:30 AZKylePAZKyleP 151 silver badge4 bronze badges 2
  • 1 Provide more info please. What is #icon, what do you mean by "not working", etc ... – Jan Hančič Commented Nov 24, 2010 at 10:32
  • Hi #icon is the image that changes to + or -. #box is the box that appears and disappears via the JQuery toggle function. – AZKyleP Commented Nov 24, 2010 at 10:33
Add a ment  | 

3 Answers 3

Reset to default 4

The .toggle() function attaches click handlers to the element, not event handlers for then an element is toggled visible, it should be attached to #icon, like this:

$("#icon").toggle(function(){
  $("#box").hide();
  this.src = "/images/icon_expand.png";
}, function() { 
  $("#box").show();
  this.src = "/images/icon_retract.png";
});

$.togle () toggles the visibility of the matched element(s). So you are using it pletely wrong.

You'll have to do something like this:

$( '#icon' ).click ( function () {
    var $this = $( this );
    var $box = $( '#box' );

    $box.toggle ();

    if ( $box.is ( ':visible' ) === true ) {
        $this.attr ( "src", "/images/icon_retract.png" );
    } else {
        $this.attr ( "src", "/images/icon_expand.png" );
    }
} );

i think, there will be a correction in Nick code and then it will work fine.
you have to first show the box and on second click you have to hide it, if is it so,
then try this

$("#icon").toggle(function(){
$("#box").show();
this.src = "/images/icon_expand.png";
}, function() {
$("#box").hide();
this.src = "/images/icon_retract.png";
});

本文标签: javascriptJQuery Toggle amp ImageStack Overflow