javascript – 测试DOM元素或JSON

假设一个函数接受一个参数,即是否包含在jQuery对象中的DOM元素或
JSON,那么如何从另一个中告诉一个? 最佳答案 你可能正在寻找这样的东西:

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;                         
};
点赞