JavaScript this from jQuery this

后端 未结 4 847
既然无缘
既然无缘 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
    0 讨论(0)
  • 2021-01-06 12:07

    this == this, whatever this is.

    this is a not jquery it is a special, somewhat convoluted, javascript keyword that describes the current scope of execution.

    your challenge may be determining or controlling what this is.

    0 讨论(0)
  • 2021-01-06 12:15

    Try to access this (DOM element) instead of $(this) (jquery object).

    0 讨论(0)
  • 2021-01-06 12:18

    I don't really understand what you're asking for here, but I'll give it a shot. Firstly, remember that jQuery is just a series of functions written in Javascript. The this keyword is literally the same in "both" contexts.

    Perhaps you want to get the actual DOM element instead of the jQuery object? You can use .get():

    // let's say there's a single paragraph element
    var obj = $('p');   // obj is a jQuery object 
    var dom = obj.get(0);  // dom is a DOM element
    
    0 讨论(0)
提交回复
热议问题