通过传递DOM对象来创建JQuery对象? [英] create JQuery object by passing DOM object?

查看:93
本文介绍了通过传递DOM对象来创建JQuery对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,让我说说:

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

所以, d 是DOM对象,

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

how can I create or convert it into jQuery object?

例如
$(d) ???

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

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

推荐答案

// 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);

或只包含在 $()中的dom元素如您所建议的:

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

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

使用 attr 来获取/设置元素属性。我不知道是否有一个单行可以转储所有元素的属性及其各自的值( firebug 为我的目的),但是您可以创建一个包含您感兴趣的所有属性名称的数组,并执行以下操作:

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:

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

或使用 $。each

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

这篇关于通过传递DOM对象来创建JQuery对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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