简体   繁体   English

如何从$(this)jQuery Object获取此DOM对象?

[英]How to get the this DOM Object from the $(this) jQuery Object?

I have a function to which a jQuery object is passed as an argument. 我有一个jQuery对象作为参数传递给的函数。 See below code. 参见下面的代码。

$('selector').click(function() {
  // $(this) is the jquery object for the DOM on which I clicked.
  test($(this));
});
function test(jqobj) {
  // Here from jqobj, I want to get back the native javascript object (I mean the this)
}

The jqobj param is an array of DOM elements so you can use jqobj参数是DOM元素的数组,因此您可以使用

     jqobj[0] 

but test the size of the array if it is not empty like 但是测试数组的大小(如果它不为空)

     jqobj.length > 0

So we can covert each other 这样我们就可以互相掩饰

//From jQuery object to Dom:
var domobject = jqueryObject.get();
//From Dom to jQuery object
var jqueryObject = jQuery(domobject);

Example: 例:

 //From Dom to jQuery object
    var overlayContent = document.createElement("div");
var __this=this; //declare out side your function.
function test(){
__this; //use __this in your function.
}

if you are sure that there will only be one element then 如果您确定只有一个元素,那么

function test(jqobj) {
  var el  = jqobj[0]
}

而不是将对象作为参数传递,您还可以将元素ID或类发送给函数。然后可以在函数内部使用getElementById方法来引用元素。

If you are not passing multiple element use like this: 如果您不传递多个元素,请按以下方式使用:

function test(jqobj) {
    var obj;
    if(jqobj[0]!=null)
    {
        obj = jqobj[0];
    }
  }

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

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