$(this) OR event.target OR var input = $(this)

前端 未结 4 1057
刺人心
刺人心 2020-12-31 23:33

jQuery is currently providing me with a fun introduction to Javascript after 12 years of surviving happily without. I\'m at the stage where I\'m trying to learn as much as I

4条回答
  •  生来不讨喜
    2021-01-01 00:16

    In my experience i would go with the following:

    $('#a_button').click(function() {
        // USING this
        var buttonValue = $(this).val();
        $(this).addClass('button_has_been_clicked');
    });
    

    The this in the context of your click callback method is a reference to the DOM event. Since you already have a reference to the DOM object it is trival to convert it into a jQuery object since a lookup is not required.

    But on a side note, if you don't need to use jQuery in your callback, then don't. You can simply get the value of the button using standard JS this.currentTarget.value.

    The other examples you mentioned require a DOM lookup, and depending on the complexity of your selector can take longer. Using a id based lookup like '#a_button' will perform better than a class based looked like .myClass.

提交回复
热议问题