检测DOM对象与jQuery对象 [英] Detect DOM object vs. jQuery Object

查看:83
本文介绍了检测DOM对象与jQuery对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想要允许传递一个常规的JavaScript DOM元素对象或一个jQuery对象的函数。如果它还不是一个jQuery对象,那么我将使它成为一个。



有没有人知道一种非常可靠的方式来检测这个。

  function functionName(elm){
//检测如果elm不是条件
中的jquery对象if(elm)elm = $(elm );

}

逻辑方法是检测其中一个属性DOM元素对象。问题是,哪个属性是最可靠的检测?



我也可以使它成为一个jquery对象,因为jQuery没有问题的东西喜欢:$($ imajQueryObjAlready);但是,这个问题的目的并不仅仅是解决问题,而是找到一个很好的方式来检测一个DOM对象与一个jQuery对象。

解决方案

要测试DOM元素,可以查看其 nodeType 属性:

  if(elm.nodeType){
//是DOM节点
}

或者您可以检查jQuery属性:

  if(elm.jquery){ 
//是一个jQuery对象
}


I have a function that I want to be able to allow passing in either a regular javascript DOM element object or a jQuery object. If its not yet a jQuery object I will then make it one.

Does anyone know of a very reliable way to detect this.

function functionName(elm){
   //Detect if elm is not a jquery object in condition
   if (elm) elm = $(elm);

}

A logical approach is to detect one of the properties of the DOM element object. The question is, which property would be the most reliable to detect?

I could also just make it a jquery object either way since jQuery doesn't have a problem with something like: $($imajQueryObjAlready); However, the purpose of this question is not to just solve the problem, but to find a good way to detect if its a DOM object vs. a jQuery object.

解决方案

To test for a DOM element, you can check its nodeType property:

if( elm.nodeType ) {
    // Was a DOM node
}

or you could check the jQuery property:

if( elm.jquery ) {
    // Was a jQuery object
}

这篇关于检测DOM对象与jQuery对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆