开发者

Test if a DOM element or JSON

开发者 https://www.devze.com 2023-01-30 02:35 出处:网络
Suppose a function accepts one argument t开发者_开发技巧hat is whether a DOM element or JSON that are wrapped in jQuery object or not, so how to tell one from the other?you\'re probably looking for so

Suppose a function accepts one argument t开发者_开发技巧hat is whether a DOM element or JSON that are wrapped in jQuery object or not, so how to tell one from the other?


you're probably looking for something like this:

var get_unknown_element = function(element) {
        var ele     = element,
            type    = Object.prototype.toString.call(ele);

        // string as passed in, we just assume it to be a jQuery (or querySelectorAll) selector string
        if(type === '[object String]') {                
            return (function(e){
               return e.length ? e : null; 
            }($(ele)));
        }
        // an object was passed in, if we have an jquery object & length > 0, just return it
        else if(type === '[object Object]' && ele.jquery && ele.length) {
            return ele;
        }    
        // native DOM object (node) was passed in, just call the jQuery constructor on it & return           
        else if(/^\[object HTML/.test(type)) {
            return $(ele);
        }
        // return null on no match
        else return null;                         
};
0

精彩评论

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