A common issue I have is getting confused what $(this) is referring to.
I often will try to give it some odd style:
$(this).css("border","10px solid red")
Which helps sometimes.
I'm stumped with the following however. My question can maybe be answered in two ways:
1) is there a universal way to 'see' what $(this) is referring to in any given situation? Perhaps in combination with firebug?
2) more specifically, any idea what $(this) should be referring to in this sample below? I assumed it would have been the input with a class of btnSave but doesn't seem to be:
$(ajaxContainer).find("input.btnSave").click(function(){
savePanel();
});
function savePanel() {
$(this).css("border","10px solid red");
};
$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.
In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.
In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.
Usually when you encounter $() , that means the developer is using a javascript library, such as jQuery. The $ symbol is the namespace for those libraries. All the functions they define begin with $. , such as $. get() .
1) Use the console in Firebug:
var obj = $(this);
console.log(obj);
2) savePanel() won't have the context correct to use $(this). You could try:
$(ajaxContainer).find("input.btnSave").click(function(){
$(this).css("border", "10px solid red");
});
First question (using Firebug):
savePanel()
in your example).$(this)
to the watch panel and expand it to view its properties."0"
, which corresponds to the first DOM node matched by the jQuery object (in this case, this
)."0"
, Firebug will highlight that DOM node on the page. If you click the value, Firebug will switch to the HTML tab and scroll to that element.Second question:
this
will refer to the <input />
element.savePanel()
, this
will refer to the window
object.If you want savePanel()
to have access to the <input />
element, there are a variety of ways to do it. The simplest in your case would be to pass it in from the anonymous function:
$(ajaxContainer).find("input.btnSave").click(function(){
savePanel($(this));
});
function savePanel(inputElement) {
inputElement.css("border","10px solid red");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With