如何检测是参数jQuery对象

Tx3*_*Tx3 9 javascript jquery

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

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

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

function myFunc(value)
{
    // check if value is jQuery or string
}
Run Code Online (Sandbox Code Playgroud)

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

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

Sir*_*rko 18

使用typeof运营商

if ( typeof value === 'string' ) {
  // it's a string
} else {
  // it's something else
}
Run Code Online (Sandbox Code Playgroud)

或者确实它是jQuery对象的一个​​实例

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

  • 至少快速测试显示'value instanceof $'运作顺利.这是我一直在寻找的东西.谢谢! (2认同)