代码之家  ›  专栏  ›  技术社区  ›  Mottie

正在检测jquery对象

  •  3
  • Mottie  · 技术社区  · 14 年前

    我正在为jquery编写一个插件,我想让它成为用户可以通过任何形式将数据传递给插件的插件。我已经解决了JSON或数组问题,但是我在尝试确定数据是否是jquery对象时遇到了问题。

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

    最后一个方法返回true,但不能保证用户正在使用 LI 标记他们的数据,所以我想我需要这样的东西:

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

    有人知道更好的方法吗?

    3 回复  |  直到 14 年前
        1
  •  9
  •   Christian C. Salvadó    14 年前

    这个 jQuery 对象(或其别名) $ 是平原 constructor function ,所有jquery对象继承自 jQuery.prototype 对象(或其别名) jQuery.fn )

    通过使用 instanceof 运算符或 isPrototypeOf 方法,例如:

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

    或:

    function isjQueryObject(obj) {
      return jQuery.fn.isPrototypeOf(obj);
    }
    
        2
  •  1
  •   Colin O'Dell    14 年前

    jquery对象只是元素的集合,存储为一个数组,附加了额外的函数和内容。所以本质上,您可以像使用常规数组一样使用jquery元素。

        3
  •  1
  •   Ken Redler    14 年前

    怎么样:

    var isJq = data instanceof jQuery;