开发者

How to tell if obj is jquery or plain javascript

This is probably a stupid question but is th开发者_开发技巧ere a way to tell programmatically if the object is jquery or just plain javascript?

For example:

Utils.Listbox.MoveItemsUp = function(listbox) {

    if(listbox.isJquery()) {
        listbox.each(function(){}); 
    }
    else {
        for(var i = 0; i < listbox.options.length; i++){}
    }
};


jQuery objects have a property called 'jquery':

>>> $('body').jquery
"1.5.2"


jQuery is just Javascript. I guess you could test for the existence of a jQuery function though:

if (foo.each)
{
    foo.each(function(...
}
else
{
    $(foo).each(function(...
}


One way is to use jQuerys $.isPlainObject function (doc) That will tell you if it was an object created using {} or new Object, a jQuery object will return false. However, note also that an array, and string and functions will also return false:

var obj = {};
var $obj = $('div');

$.isPlainObject(obj); //returns true
$.isPlainObject($obj); //returns false


To test if an object is a jQuery object, you check the jquery attribute of it. so:

<script>
Utils.Listbox.isJquery = function()
{
    return typeof this.jquery != 'undefined';
}
</script>


What you should remember is that whenever your within a callback the object this is always an native entity and not a jquery object.

for example:

a = $('a').each(function(){
    //'this' is ALWAYS an native object
});

a will always be an instance of jQuery unless your using a specific method that returns a type such as json object, boolean, string etc.

if your recurving variable from a function that's out of your control and you want to know if it's a jQuery object you can do the following:

if(!listbox || !listbox.jquery)
{
     listbox = $(listbox)
}
//the variable is now always going to be a jQuery object.

the reason for this is that jquery always stores an reference to its version within a selected context

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜