jquery .click being called multiple times

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

    You are setting a new .click() eventHandler each time you keep clicking it (which in turn creates even more events). On a side note, try to never use onclick / onmouseover / onmouseout / etc events on DOM elements. In Internet explorer these create script blocks (that you can visibly see if you use Visual Studio. Pages with thousands of these slow down performance tremendously!

    It looks like you are trying to achieve this:

    jsFiddle DEMO

    $("#test").on('click', function() {
        var this$   = $(this),
            _status = !!this$.data('status'); // force to boolean
                      // ^will default to false since we have no data-status attribute yet
    
        this$.html(_status ? 'Hello' : 'Goodbye')
             .data('status', !_status);
    });​
    

提交回复
热议问题