通过传递DOM对象来创建JQuery对象?

时间:2022-12-05 16:15:37

So, let say I have this:

所以,让我说我有这个:

var d = document.createElement('div');
d.id = "whatever";`

So, d is the DOM object,

所以,d是DOM对象,

how can I create or convert it into jQuery object?

如何创建或转换为jQuery对象?

e.g. $(d) ???

例如$(d)???

and, how to 'read' all attributes of the jQuery object? just like the var_dump of PHP.

以及如何“读取”jQuery对象的所有属性?就像PHP的var_dump一样。

1 个解决方案

#1


23  

// create a jQuery-boosted div
$div = $('<div></div>');
$div.attr('id','someId');
alert($div.attr('id'));

// to get the DOM element:
var div = $div[0];

// or
var div = $div.get(0);

or just wrap the dom element in $() as you suggested:

或者只是按照你的建议将dom元素包装在$()中:

$(d).attr('id','someId');
$(d).blah();

Use attr to get/set element attributes. I'm not sure if there's a one-liner that can dump all of an element's attributes and their respective values (firebug serves that purpose for me), but you can create an array with all the attribute names you're interested in, and do something like:

使用attr来获取/设置元素属性。我不确定是否有一个可以转储所有元素属性及其各自值的单行(firebug为我提供了这个目的),但你可以创建一个包含你感兴趣的所有属性名称的数组,并且做类似的事情:

var attr = ['name', 'id', 'src', 'foo'];
var len = attr.length;
for (var i = 0; i < len; i++) 
    alert($(d).attr(attr[i]));

or using $.each:

或使用$ .each:

$.each(['name', 'id', 'src', 'foo'], function(i,val) {
    alert( 'Attribute: ' + val + ' Value: ' + $(d).attr(val) );
});

#1


23  

// create a jQuery-boosted div
$div = $('<div></div>');
$div.attr('id','someId');
alert($div.attr('id'));

// to get the DOM element:
var div = $div[0];

// or
var div = $div.get(0);

or just wrap the dom element in $() as you suggested:

或者只是按照你的建议将dom元素包装在$()中:

$(d).attr('id','someId');
$(d).blah();

Use attr to get/set element attributes. I'm not sure if there's a one-liner that can dump all of an element's attributes and their respective values (firebug serves that purpose for me), but you can create an array with all the attribute names you're interested in, and do something like:

使用attr来获取/设置元素属性。我不确定是否有一个可以转储所有元素属性及其各自值的单行(firebug为我提供了这个目的),但你可以创建一个包含你感兴趣的所有属性名称的数组,并且做类似的事情:

var attr = ['name', 'id', 'src', 'foo'];
var len = attr.length;
for (var i = 0; i < len; i++) 
    alert($(d).attr(attr[i]));

or using $.each:

或使用$ .each:

$.each(['name', 'id', 'src', 'foo'], function(i,val) {
    alert( 'Attribute: ' + val + ' Value: ' + $(d).attr(val) );
});