开发者

jquery toggle event within toggle event creates unexpected behavior

$('button').toggle({
    function(e){
        //turn on effects for all elements clicked
        $('*').toggle(
            function(e){
                //some nice effects when you click on elements
            },
            function(e){
                //nice effects turned off when you click a开发者_如何学运维gain.
            }
        );
    },

    function(e){
        // turn off all effects. aka unbind all click event
    });
});

It doesn't quite behave the way i expected. I wanted to basically, on clicking the button, that effects are turned on when you click an element. Its turned off when you click that element again. Click the button and all effects are disabled.

However, what i end up with is:

  • click the button
  • effects are turned on when i click an element
  • effects do not turn off when i click it again.
  • effects turn off when i click once more.

also

  • click the button.
  • effects turned on.
  • click button again
  • effects doesn't turn off.
  • click button again
  • effects turn off.

why does it do this ??


I'm not exactly sure I understand what you're trying to do, but my advice is to never use the $('*') selector. Do you really, really want your 'effects' to operate on EVERY DOM element in the page? Remember, that includes your "turn off/turn on" button.

I constructed an example which I think does what you're trying to do:

<head>
    <title>Test</title>
    <style type="text/css">
        .effectsOn {
            border: 1px solid blue;
            cursor: pointer;
        }
    </style>
    <script src="jquery.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#btnToggle").toggle(function() {
                // turn on effects for all elements clicked
                $("li").addClass("effectsOn").toggle(function() {
                    // some nice effects when you click on elements
                    alert("test");
                },
                function() {
                    // nice effects disabled when you click again
                    $(this).removeClass("effectsOn").unbind();
                });
            },
            function() {
                // turn off all effects; aka unbind all click event
                $("li").removeClass("effectsOn").unbind();
            });
        });
    </script>
</head>
<body>
    <input type="button" id="btnToggle" value="Toggle effects" />
    <ul>
        <li>This is like, you know, a test.</li>
        <li>This is like, you know, a test.</li>
        <li>This is like, you know, a test.</li>
        <li>This is like, you know, a test.</li>
    </ul>
</body>

The key here was in using the "this" keyword to refer to the object being toggled, and (to reiterate what I said above) NOT using the $('*') selector.

Is this what you meant?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜