Jquery 在当前附加的元素上设置ID

Jquery 在当前附加的元素上设置ID,jquery,Jquery,我有一个如果您只需要为第一个子元素设置id属性,您可以使用jQuery这样做: var template = $('#element-template').html(); var $output = $('#output'); $output.append(template).children(':first').attr('id', 'my-element');​ 示例:我将使模板变量保存jquery对象而不是html 这样,您就可以创建它并直接在其上添加id var template =

我有一个
如果您只需要为第一个子元素设置id属性,您可以使用jQuery这样做:

var template = $('#element-template').html();
var $output = $('#output');
$output.append(template).children(':first').attr('id', 'my-element');​

示例:

我将使
模板
变量保存jquery对象而不是html

这样,您就可以创建它并直接在其上添加id

var template = $( $('#element-template').html() );

$('#output').append( template.clone().attr('id','my-element') );
演示在

您可以使用
find('div:first')


.

啊,我把美元()的外包装弄丢了。。。谢谢但是我需要克隆它吗?如果没有:@JohnB.,它似乎工作得很好。如果没有它,只需一次附加。。我的想法是,因为它是一个模板,你可能想重用它…我明白,似乎是最好的解决方案,我的情况。谢谢!
var template = $('#element-template').html();
$('#output').append(template).parent().find('.element-container').attr('id', 'my-element');​
var template = $('#element-template').html();
var $output = $('#output');
$output.append(template).children(':first').attr('id', 'my-element');​
var template = $( $('#element-template').html() );

$('#output').append( template.clone().attr('id','my-element') );
$('#output').append($('#element-template').html())
.find('div:first').attr('id', 'my-element');​