如何创建一个DOM节点作为对象? [英] How to create a DOM node as an object?

查看:212
本文介绍了如何创建一个DOM节点作为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个DOM节点,设置id属性,然后将其附加到body。以下内容似乎不起作用,因为jQuery看不到我的模板作为一个对象:

I would like to create a DOM node, set the 'id' attribute and then append it to 'body'. The following seems not to work because jQuery doesn't see my template as an object:

var template = "<li><div class='bar'>bla</div></li>";
template.find('li').attr('id','1234');
$(body).append(template);

我如何告诉jQuery将其视为一个对象,因此find()可以正常工作? p>

How can I tell jQuery to treat this as an object so find() works on it?

推荐答案

我先把它放在DOM里。我不知道为什么我的第一个例子失败了。这真的很奇怪。

I'd put it in the DOM first. I'm not sure why my first example failed. That's really weird.

var e = $("<ul><li><div class='bar'>bla</div></li></ul>");
$('li', e).attr('id','a1234');  // set the attribute 
$('body').append(e); // put it into the DOM     

放e(返回元素)给出jQuery 上下文,用于应用CSS选择器。这使得它不能将ID应用于DOM树中的其他元素。

Putting e (the returns elements) gives jQuery context under which to apply the CSS selector. This keeps it from applying the ID to other elements in the DOM tree.

这个问题似乎是你没有使用UL。如果你把一个裸体的li放在DOM树中,你会有问题。我以为它可以处理/解决这个问题,但它不能。

The issue appears to be that you aren't using the UL. If you put a naked li in the DOM tree, you're going to have issues. I thought it could handle/workaround this, but it can't.

您可能不会将裸体的LI放在您的DOM树中进行真实实施,但是UL是必需的。叹息。

You may not be putting naked LI's in your DOM tree for your "real" implementation, but the UL's are necessary for this to work. Sigh.

示例:
http:// jsbin。 com / iceqo

顺便说一下,您可能也会对 microtemplating

By the way, you may also be interested in microtemplating.

这篇关于如何创建一个DOM节点作为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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