JQuery $(this) selector function and limitations

后端 未结 5 1142
南方客
南方客 2020-12-01 08:31

I need help understanding $(this). Is it possible to narrow the focus of \'this\' within the parentheses or does \"this\" preclude the use of any other attributes?

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 09:04

    this isn't a jQuery "thing", but a basic JavaScript one. It can't be re-written the way you have in examples because it's an object, in particular either a DOM element or a jQuery object (depending on what context you're in). So if you did this:

     $(this + " div")
    

    What you'd really be doing is calling .toString() on this to concatenate the strings, resulting in:

     $("[object Object] div")
    

    ....which isn't a valid selector.

    As for further reading, I believe this article continues to be one of the best references/resources to learn what this (a context keyword) means.


    Per comment requests, some examples of what this is in various places:

    • Event handlers, for example: $("selector").click(function() { alert(this); });
      • this refers to the DOM element the event handler is being triggered on.
    • Inside a jQuery plugin, for example: $.fn.myPlugin = function() { alert(this); });
      • this is the jQuery object the plugin was called/chained on, for example: $("selector").myPlugin();, this is that $("selector") jQuery object.
    • Inside any generic function, for example: function myFunc() { alert(this); };
      • this is the context you're in, whether it be an object or something else, a few examples:
      • $("selector").click(myFunc); - this is the DOM element, like above
      • $("selector").click(function() { myFunc(); }); - this is the global content, window
      • myFunc.call(whatThisIs, arg1, arg2); - this is whatThisIs
        • See Function.call() and Function.apply() for more info

提交回复
热议问题