javascript - Detecting jQuery Object - Stack Overflow

I'm writing a plugin for jQuery and I want to make it so the user can pass data to the plugin in a

I'm writing a plugin for jQuery and I want to make it so the user can pass data to the plugin in any form. I have the JSON or array problem worked out, but I'm having trouble trying to determine if the data is a jQuery object.

data = $('#list li');
console.debug( $.isPlainObject(data) );   // false
console.debug( $.isArray(data) );         // false
console.debug( data[0].tagName == "LI" ); // true, but see note below

The last method returns true, but there is no guarantee that the user is using an LI tag for their data, so I think I need something like this:

if ( $.isjQueryObject(data) ) { /* do something */ }

Does anyone know a better method?

I'm writing a plugin for jQuery and I want to make it so the user can pass data to the plugin in any form. I have the JSON or array problem worked out, but I'm having trouble trying to determine if the data is a jQuery object.

data = $('#list li');
console.debug( $.isPlainObject(data) );   // false
console.debug( $.isArray(data) );         // false
console.debug( data[0].tagName == "LI" ); // true, but see note below

The last method returns true, but there is no guarantee that the user is using an LI tag for their data, so I think I need something like this:

if ( $.isjQueryObject(data) ) { /* do something */ }

Does anyone know a better method?

Share Improve this question edited Jul 4, 2010 at 2:29 Christian C. Salvadó 829k185 gold badges928 silver badges845 bronze badges asked Jul 4, 2010 at 1:39 MottieMottie 86.5k30 gold badges130 silver badges248 bronze badges 1
  • Apparently, there is a Ben Alman plugin for that - benalman./projects/jquery-misc-plugins/#isjquery – Mottie Commented Oct 9, 2010 at 16:25
Add a ment  | 

3 Answers 3

Reset to default 9

The jQuery object (or its alias $) is a plain constructor function, all jQuery objects inherit from the jQuery.prototype object (or its alias jQuery.fn).

You can check if an object exists in the prototype chain of other object, by using either the instanceof operator or the isPrototypeOf method, for example:

function isjQueryObject(obj) {
  return obj instanceof jQuery;
}

Or:

function isjQueryObject(obj) {
  return jQuery.fn.isPrototypeOf(obj);
}

The jQuery object is simply a collection of elements, stored as an array, with additional functions and stuff attached. So essentially you could use the jQuery elements just like you would a regular array.

How about:

var isJq = data instanceof jQuery;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745576057a4633967.html

相关推荐

  • javascript - Detecting jQuery Object - Stack Overflow

    I'm writing a plugin for jQuery and I want to make it so the user can pass data to the plugin in a

    10小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信