jquery .click being called multiple times

前端 未结 8 2341
小蘑菇
小蘑菇 2021-02-20 11:12

I am getting unexpected results with jQuery trying to set the \"click\" method of a div. Please see this jsfiddle. Be sure to open the console window. Click the word a few times

8条回答
  •  余生分开走
    2021-02-20 11:31

    The jQuery click function doesn't overwrite a previous click handler but instead adds the new one to a queue. So when click is called again, a new click handler is added along with all the old ones.

    To prevent this, you just need to clear the old handlers before defining your new one.

    function toggleDiv(status)
    {
        console.log("toggleDiv(" + status + ")");
        if (status) {
            $("#test").html("Goodbye");
        }
        else  {
            $("#test").html("Hello");
        }
    
        $("#test").unbind();
    
        $("#test").click(function() {
            toggleDiv(!status);
        });
    }​
    

    You may also want to look at the .toggle() event handler.

    UPDATE: To be clearer about .toggle(), this will also do what you want:

    $("#test").toggle(
        function(event) { $(event.target).html("Goodbye"); },
        function(event) { $(event.target).html("Hello"); }
    );
    

提交回复
热议问题