开发者

jQuery Toggle switch images

开发者 https://www.devze.com 2023-01-03 01:56 出处:网络
I have a situation where I am not understanding jQuery\'s Toggle. I have two buttons, both of them open the same content and when you click on either button thecontent should open or close and th开发

I have a situation where I am not understanding jQuery's Toggle.

I have two buttons, both of them open the same content and when you click on either button the content should open or close and th开发者_开发百科e attribute changes the button from open to closed. (So both buttons do the same function).

Only thing is, when I click on the top button and it opens my content and then click on the lower button to close it, the image attributes are switched incorrectly.

Here's a very stripped down version of what my code looks like and I would appreciate some help.

<script language="javascript" type="text/javascript">
    $(function () {

        var open = false;

        $("#button1, #button2").toggle(
            function () {
                open = true;
                $("#button1").attr("src", "images/btn-open.gif");
                $("#button2").attr("src", "images/btn-open.gif");
            },
            function () {
                if (open) {
                    $("#button1").attr("src", "images/btn-closed.gif");
                    $("#button2").attr("src", "images/btn-closed.gif");

                } else {
                    $("#button1").attr("src", "images/btn-open.gif");
                    $("#button2").attr("src", "images/btn-open.gif");

                }
                open = false;

            }
        );


    });
</script>

<img id="button1" src="images/btn-open.gif"></img>
<br />
<br />
<br />
<br />
<img id="button2" src="images/btn-open.gif"></img>


.toggle() will cycle between the n (usually 2, but it's not limited to 2) provided functions on each click per element, but you want one toggle for both buttons, not each one toggling indepdently, so do a check and use .click(), something like this:

var open = false;
$("#button1, #button2").click(function () {
  open = !open; //toggle it
  $("#button1, #button2") //set the src based on the new state
     .attr("src", "images/btn-" + (open ? "open" : "closed") + ".gif");
});

I also combined your selectors to make it a bit neater, it's the same effect though :) I'm not 100% sure from your images names so you may need to switch the boolean around, but you get the idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消