Check if 'this' is $(this) or just plain old 'this'
I have one function:
function myFunction(){
var id = $(this).attr('id');
}
Now sometimes, myFunction gets called with $(this) as the context but sometimes the context is just 'this'.
In one line how can I do something similar to this:
if(this == $(this)){
var e = $(this);
}
Basically a test to see if 'this' is a jQuery 'this' or a JS 'this'.
Possible?
if (this.jquery) { // refers to jQuery version
// jQuery object
}
Alternatively:
if (this instanceof jQuery) { // prototype chain
// jQuery object
}
However, as others have said, it doesn't really matter, $(this)
will work whether or not this
is already a jQuery
object or a DOM element.
当this
是一个jQuery对象或者它不是时,你也可以做var e = $(this)
。
One way to deal with it would just be to always wrap it in $(...)
. Wrapping a jQuery object like that creates a clone (see the jQuery docs), so this HTML:
<a href="test" id="test-link">Test Link</a>
with this JS:
var link = $('#test-link');
var doubleWrappedLink = $(link);
alert(doubleWrappedLink.attr('href'));
will correctly pop up "test".
链接地址: http://www.djcxy.com/p/83936.html