Detect DOM object vs. jQuery Object

后端 未结 6 1549
忘掉有多难
忘掉有多难 2021-01-31 08:55

I have a function that I want to be able to allow passing in either a regular javascript DOM element object or a jQuery object. If its not yet a jQuery object I will then make i

6条回答
  •  天命终不由人
    2021-01-31 09:35

    The easiest way is to simply pass it into the jQuery function either way. If it's already a jQuery object, it will return it unchanged:

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

    From the jQuery source code, this is what's happening:

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

    Where makeArray is merging the new (default) jQuery object with the passed in one.

提交回复
热议问题