jquery .click being called multiple times

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

    You should bind the click event outside the toggleDiv function. The current code will register new click event handler every time the elements in $('#test') is clicked, with exponential growth (since all previous click handler will generate a new click handler, so the number of handlers will double with every click).

    0 讨论(0)
  • 2021-02-20 11:36

    You're re-registering the click handler over and over recursively.

    One correct solution (of many possible variations) is this:

    $(function() {
        var status = false;
    
        $('#test').click(function() {
            status = !status;
            $(this).html(status ? 'Goodbye' : 'Hello');
        });
    });
    

    and then you need to remove the onclick attribute from the HTML - it's not good to mix DOM0 and DOM3 event handling.

    See http://jsfiddle.net/alnitak/8aBxp/

    0 讨论(0)
提交回复
热议问题