Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何判断obj是jquery还是纯javascript_Javascript_Jquery - Fatal编程技术网

如何判断obj是jquery还是纯javascript

如何判断obj是jquery还是纯javascript,javascript,jquery,Javascript,Jquery,这可能是一个愚蠢的问题,但是有没有办法通过编程告诉我们对象是jquery还是纯javascript 例如: Utils.Listbox.MoveItemsUp = function(listbox) { if(listbox.isJquery()) { listbox.each(function(){}); } else { for(var i = 0; i < listbox.options.length; i++){}

这可能是一个愚蠢的问题,但是有没有办法通过编程告诉我们对象是jquery还是纯javascript

例如:

Utils.Listbox.MoveItemsUp = function(listbox) {

    if(listbox.isJquery()) {
        listbox.each(function(){}); 
    }
    else {
        for(var i = 0; i < listbox.options.length; i++){}
    }
};
a = $('a').each(function(){
    //'this' is ALWAYS an native object
});
Utils.Listbox.MoveItemsUp=函数(Listbox){
if(listbox.isJquery()){
每个(函数(){});
}
否则{
对于(var i=0;i
jQuery对象有一个名为“jQuery”的属性:

>>> $('body').jquery
"1.5.2"
jQuery只是Javascript。我想您可以测试jQuery函数是否存在:

if (foo.each)
{
    foo.each(function(...
}
else
{
    $(foo).each(function(...
}

一种方法是使用jQuerys
$。isPlainObject
函数()告诉您它是使用
{}
新对象创建的对象,jQuery对象将返回false。但是,还要注意,数组、字符串和函数也将返回false:

var obj = {};
var $obj = $('div');

$.isPlainObject(obj); //returns true
$.isPlainObject($obj); //returns false

您应该记住的是,每当在回调中调用时,对象
this
始终是本机实体,而不是jquery对象

例如:

Utils.Listbox.MoveItemsUp = function(listbox) {

    if(listbox.isJquery()) {
        listbox.each(function(){}); 
    }
    else {
        for(var i = 0; i < listbox.options.length; i++){}
    }
};
a = $('a').each(function(){
    //'this' is ALWAYS an native object
});
a
将始终是jQuery的实例,除非您使用返回类型(如json对象、布尔值、字符串等)的特定方法

如果您的递归变量来自无法控制的函数,并且您想知道它是否是jQuery对象,则可以执行以下操作:

if(!listbox || !listbox.jquery)
{
     listbox = $(listbox)
}
//the variable is now always going to be a jQuery object.

原因是jquery总是在选定的上下文中存储对其版本的引用

要测试对象是否是jquery对象,请检查它的
jquery
属性。因此:

<script>
Utils.Listbox.isJquery = function()
{
    return typeof this.jquery != 'undefined';
}
</script>

Utils.Listbox.isJquery=函数()
{
返回this.jquery的类型!=“未定义”;
}

这正是我想要的,非常感谢Marco!