我正在为 jQuery 编写一个插件,我想做一个这样用户就可以以任何形式将数据传递给插件。我解决了 JSON 或数组问题,但在尝试确定数据是否为 jQuery 对象时遇到问题。
data = $('#list li');
console.debug( $.isPlainObject(data) ); // false
console.debug( $.isArray(data) ); // false
console.debug( data[0].tagName == "LI" ); // true, but see note below
最后一个方法返回 true,但不能保证用户正在为他们的数据使用 LI
标记,所以我想我需要这样的东西:
if ( $.isjQueryObject(data) ) { /* do something */ }
有没有人知道更好的方法?
最佳答案
jQuery
对象(或其别名 $
)是一个普通的 constructor function , 所有 jQuery 对象都继承自 jQuery.prototype
对象(或其别名 jQuery.fn
)。
您可以使用instanceof
来检查一个对象是否存在于其他对象的原型(prototype)链中。运算符(operator)或 isPrototypeOf
方法,例如:
function isjQueryObject(obj) {
return obj instanceof jQuery;
}
或者:
function isjQueryObject(obj) {
return jQuery.fn.isPrototypeOf(obj);
}
关于javascript - 检测 jQuery 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3173432/