Javascript 如何以编程方式检测对象是否为jQuery对象?
如何以编程方式检测对象是否为jQuery对象?例如:Javascript 如何以编程方式检测对象是否为jQuery对象?,javascript,jquery,Javascript,Jquery,如何以编程方式检测对象是否为jQuery对象?例如: // 1. declare some variables var vars = [1, 'hello', ['bye', 3], $(body), { say: 'hi' }]; // 2. ??? : implement function that tests whether its parameter is a jQuery object function isjQuery(arg) { /* ??? */ } // 3. profi
// 1. declare some variables
var vars = [1, 'hello', ['bye', 3], $(body), { say: 'hi' }];
// 2. ??? : implement function that tests whether its parameter is a jQuery object
function isjQuery(arg) { /* ??? */ }
// 3. profit
var test = $.map(vars, isjQuery); /* expected [ false, false, false, true, false ] */
API文档化的最简单方法是测试属性:
function isjQuery(arg) {
return !!arg.jquery;
}
但是,如果您想确定它是一个jQuery对象,而不是其他具有伪.jQuery
属性的对象,那么其他答案建议使用jQuery的实例,并测试构造函数
(该属性在形式上是一个表示jQuery版本的字符串,但API示例使用它来测试对象是否为jQuery对象。)有几种方法,但最清晰的(在我看来)是:
function isjQuery(arg) { return arg instanceof jQuery; }
我想你可以信赖
if ( vars[i] instanceof jQuery ) {
// do something with this jQuery object
}
但我也发现了这些方法:
obj && obj.constructor == jQuery
obj && obj.jquery