Definition of $ (this) in jquery

The general problem I am facing is confused with what $ (this) means.

I often try to give it an odd style:

$(this).css("border","10px solid red")

Sometimes it helps.

However, I am puzzled by the following. My question can be answered in two ways:

1) Is there a universal way to β€œsee” what $ (this) refers to in this task? Perhaps in combination with firebug?

2), in particular, any idea for which $ (this) should be used in this example? I assumed that this would be an input with the btnSave class, but did not seem to be:

$(ajaxContainer).find("input.btnSave").click(function(){
    savePanel();
});

function savePanel() {
    $(this).css("border","10px solid red");
};
+5
source share
4 answers

1) Use the console in Firebug:

var obj = $(this);
console.log(obj);

2) savePanel () will not use the context to use $ (this). You may try:

$(ajaxContainer).find("input.btnSave").click(function(){
    $(this).css("border", "10px solid red");
});
+9

( Firebug):

  • - , (, savePanel() ).
  • , $(this) , .
  • "0", DOM node, jQuery ( this).
  • "0", Firebug DOM node . , Firebug HTML .

:

  • this <input />.
  • savePanel(), this window.

, savePanel() <input />, . :

$(ajaxContainer).find("input.btnSave").click(function(){
  savePanel($(this));
});

function savePanel(inputElement) {
  inputElement.css("border","10px solid red");
}
+4

JavaScript , ( ). savePanel , , . , :

$(ajaxContainer).find("input.btnSave").click(function(){
    savePanel.call(this);
});

// OR

$(ajaxContainer).find("input.btnSave").click(function(){
    savePanel.apply(this, arguments);
});

function savePanel() {
    $(this).css("border","10px solid red");
};
+1

"this" javascript is often a source of confusion because it looks syntactically like a variable and therefore implies the idea of ​​passing it on. In fact, β€œthis” is more like a function and always returns the current execution context, that is, the context to which the current function was called.

If I'm not mistaken, jquery tries to execute a callback in the context caused by the callback binding, i.e.

 object1.object2.object3.bindSomeCallback(function() {
        object3 will be "this" in the callback
 })
0
source

All Articles