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

检测DOM对象与jQuery对象

  •  32
  • Mechlar  · 技术社区  · 15 年前

    我有一个函数,希望能够允许传入常规javascript DOM元素对象或jQuery对象。如果它还不是jQuery对象,那么我将使它成为一个。

    有没有人知道一个非常可靠的方法来检测这个。

    function functionName(elm){
       //Detect if elm is not a jquery object in condition
       if (elm) elm = $(elm);
    
    }
    

    我也可以任意将其设置为jquery对象,因为jquery不存在诸如:$($imajQueryObjAlready)之类的问题;但是,这个问题的目的不仅仅是解决问题,而是找到一个好的方法来检测它是DOM对象还是jquery对象。

    6 回复  |  直到 13 年前
        1
  •  60
  •   user113716    15 年前

    要测试DOM元素,可以检查 nodeType 属性:

    if( elm.nodeType ) {
        // Was a DOM node
    }
    

    if( elm.jquery ) {
        // Was a jQuery object
    }
    
        2
  •  13
  •   karim79    15 年前

    要测试jQuery对象,可以使用 instanceof

    if(elm instanceof jQuery) {
        ...
    }
    

    或:

    if(elm instanceof $) {
        ...
    }
    
        3
  •  8
  •   AndreKR    15 年前

    if ( selector.nodeType )
    

    (jQuery 1.4.3,第109行)

        4
  •  7
  •   Zack Bloom    15 年前

    最简单的方法是简单地将其传递到jQuery函数中。如果它已经是一个jQuery对象,它将原封不动地返回它:

    function(elem){
       elem = $(elem);
       ...
    }
    

    从jQuery源代码中可以看出:

    if (selector.selector !== undefined) {
        this.selector = selector.selector;
        this.context = selector.context;
    }
    
    return jQuery.makeArray( selector, this );
    

        5
  •  6
  •   Han Seoul-Oh    15 年前

    elm instanceof jQuery 是最简单的方法 elm.nodeType 会出错的 {nodeType:1} 对于DOM元素,并测试 elm.jquery {jquery:$()} 对于jQuery对象,除了不能保证将来的jQuery对象不会有 jquery 财产。

        6
  •  0
  •   Bob Stein    9 年前

    优雅的方式:

    function is_jquery_object(x) {
        return window.jQuery && x instanceof jQuery;
    }
    
    function is_dom_object(x) {
        return window.HTMLElement && x instanceof HTMLElement;
    }
    

    当然 它是DOM或jQuery对象,使用这些测试。(在 window 如果未定义类(例如jQuery未能加载),则测试有助于函数正常失败。)