简体   繁体   English

JQuery Toggle&Image

[英]JQuery Toggle & Image

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! 谢谢!

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: .toggle()函数将click处理程序附加到元素,而不是事件处理程序,然后元素切换为可见,它应该附加到#icon ,如下所示:

$("#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). $ .togle()切换匹配元素的可见性。 So you are using it completely 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"; this.src =“/ images / icon_expand.png”;
}, function() { ,function(){
$("#box").hide(); $( “#箱”)隐藏()。
this.src = "/images/icon_retract.png"; this.src =“/ images/icon_retract.png”;
}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM