如何检测是参数jQuery对象

时间:2012-05-23 13:58:30

标签: javascript jquery

我想创建可以与Id一起使用或通过传递jQuery对象的函数。

var $myVar = $('#myId');

myFunc($myVar);
myFunc('myId');

function myFunc(value)
{
    // check if value is jQuery or string
}

如何检测传递给函数的参数类型?

注意! This问题不一样。我不想传递像#id.myClass这样的选择器字符串。我想像示例中那样传递jQuery对象。

7 个答案:

答案 0 :(得分:18)

使用typeof运算符

if ( typeof value === 'string' ) {
  // it's a string
} else {
  // it's something else
}

或者确定它是jQuery对象的实例

if ( typeof value === 'string' ) {
  // it's a string
} else if ( value instanceof $) {
  // it's a jQuery object
} else {
  // something unwanted
}

答案 1 :(得分:3)

每个jquery对象都有一个属性jquery。当然,如果您的对象具有jquery属性,那么这将失败...但如果您愿意,可以进行更严格的检查......

function(o) {
    if(typeof o == 'object' && o.jquery) // it's jquery object.
}

答案 2 :(得分:0)

检查参数的类型是否不够?

function myfunc(arg)
{
    if(typeof arg == 'string')
    {

    }
    else if(typeof arg == 'object')
    {

    }  
}

选中Fiddle

答案 3 :(得分:0)

function myFunc(value)
{
   if (typeof value == "string") {
      //it's a string
   }
   else if (value != null && typeof value == "object"} {
      //it's an object (presumably jQuery object)
   }
   else {
      //it's null or something else
   }


}

答案 4 :(得分:0)

试试这个:

function myFunc(value)
{
   if(typeof value === 'object') {
   }
   else{
   }
}

答案 5 :(得分:0)

function myFunc(value)
{
  if(typeof(value) == 'string')
    //this is a string
  else if (value === jQuery)
    //this is jQuery
  else if (typeof(value) == 'object')
    //this is an object
}

注意:在控制台中执行此操作:

> jQuery
function (a,b){return new e.fn.init(a,b,h)}
> var value = jQuery
undefined
> value
function (a,b){return new e.fn.init(a,b,h)}
> value === jQuery
true

答案 6 :(得分:0)

尝试使用typeof,例如:

var $myVar = $('#myId');

myFunc($myVar);
myFunc('myId');

function myFunc( value ){
    // check if value is jQuery or string
    switch( typeof value ) {
        case 'object':
        // is object
        break;

        case 'string':
        // is string
        break;

        // etc etc.
    }
}