最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery Toggle & Image - Stack Overflow

programmeradmin2浏览0评论

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";
});

发布评论

评论列表(0)

  1. 暂无评论