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

前端 未结 4 1058
刺人心
刺人心 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:13

    I built a little example to demonstrate how this and e.target actually work: http://jsfiddle.net/xZAVa/

    0 讨论(0)
  • 2021-01-01 00:16

    this and event.target are not always the same. this refers to the element you assigned the listener to ( in this case the '#a_button' ). event.target however is the element that actualy triggered the event, which can be a childnode of #a_button.

    So $(this) is the thing you are looking for.

    See reference: http://api.jquery.com/event.target/

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-01 00:26

    I may be wrong, but this and event.target are both just different references to the same element.

    this and event.target are not always references to the same element. But in answer to your question, var thisButton = $(this); is definitely the winner. If you were writing C# code, you would never do the following:

    this.Controls[0].Controls[0].Text = "Foo";
    this.Controls[0].Controls[0].Controls.Clear();
    

    You would do this:

    var control = this.Controls[0].Controls[0];
    

    So you probably should never re-use $(this) more than once either. Althought it's trivial to convert this from a DOM element to a jQuery object, it's still an unnecessary overhead.

    However, sometimes you need to gear back from optimisation to make sure your code maintains it's readability.

    Another option of course is just to change what this is. This is javascript afteral:

    this = $(this); // Now `this` is your jQuery object
    

    Disclaimer: I only just tried the above and it seemed to work. Might have some issues though.

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