JavaScript this from jQuery this

后端 未结 4 846
既然无缘
既然无缘 2021-01-06 11:24

Is there a way to get JavaScript this from jQuery this?

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 12:00

    There is:

    $('a').click(function(){
       var jqueryobject = $(this);
       var domelement   = this;
    }); 
    

    Within such a closure, this always represent the native DOM element which must/can be wrapped into a jQuery object.

    If you already got a jQuery object and need to get the DOM element either use

    var DOMelement = $(this)[0];
    

    or

    var DOMelement = $(this).get(0);
    

    Since jQuery objects are array like objects you can always grab them with standard array access [] notation. The jQuery method .get() will actually do the same. With both ways, you'll receive the DOM element at that array position.

    General - what is this ?

    • this contains a reference to the object of invocation
    • this allows a method to know what object it is concerned with
    • this allows a single function object to service many functions
    • So this is the most important part of all protoypal inheritance things

提交回复
热议问题