jquery .click being called multiple times

前端 未结 8 2339
小蘑菇
小蘑菇 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:23

    Most likely you are running toggleDiv mutliple times, resulting in the click event being bound multiple times. Bind the click event outside of the toggleDiv function.

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

提交回复
热议问题