如何以编程方式检测对象是否是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. profit
var test = $.map(vars, isjQuery); /* expected [ false, false, false, true, false ] */
Run Code Online (Sandbox Code Playgroud)
最简单的API记录方法是测试.jquery属性:
function isjQuery(arg) {
return !!arg.jquery;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您想确定它是一个jQuery对象而不是其他具有虚假.jquery属性的对象,那么其他答案instanceof jQuery也会建议并测试构造函数.
(该.jquery属性正式表示jQuery版本的字符串,但API示例使用它来测试对象是否是jQuery对象.)
我想你可以信赖
if ( vars[i] instanceof jQuery ) {
// do something with this jQuery object
}
Run Code Online (Sandbox Code Playgroud)
但我也在这里找到了这些方法:
obj && obj.constructor == jQuery
obj && obj.jquery
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
877 次 |
| 最近记录: |