简体   繁体   English

如何判断一个元素是 jquery DOM 元素还是原版?

[英]how can I tell if an element is a jquery DOM element or vanilla?

How can I tell if a DOM element $('.hello') is either a jquery element or vanilla javascript?如何判断 DOM 元素$('.hello')是 jquery 元素还是普通 javascript? I have code that takes in a jquery element and performs operations to it, but I would like the code to also take in vanilla javascript elements and do the same thing.我有接受 jquery 元素并对它执行操作的代码,但我希望代码也接受普通 javascript 元素并做同样的事情。 How would you go about doing this?你会怎么做呢? Basically, the code works regardless of whether the element is jquery or vanilla.基本上,无论元素是 jquery 还是 vanilla,代码都可以正常工作。

You can check it by (obj instanceof jQuery) === true您可以通过(obj instanceof jQuery) === true检查它

For example -例如 -

function doSomething(element) {

  $elm = (element instanceof jQuery !== true) ? $(element) : element;
  // do something with $elm and jQuery

}

You can also re-wrap the element with $() even if it's already a jQuery object as it's allowed.您也可以使用 $() 重新包装元素,即使它已经是 jQuery object 也是允许的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM