我有以下jQuery代码可以工作,但它让我思考,如果有可能对附加的内容执行追加操作,而无需指定我想要追加的内容. append().append()没有做到这一点,它只是将两个元素放在一起,而不是第一个append()动作的子元素.
作品:
- var container = $('#container'),child = 'child';
- $('#container').append($('<div/>',{
- 'id' : 'child'
- }));
- $('#' + child).append($('<a/>',{
- 'class' : 'close','href' : 'javascript:;',html : 'close',click : function(e){
- e.preventDefault();
- $('#' + child).remove();
- }
- }));
不起作用:
- var container = $('#container'),{
- 'id' : 'child'
- })).append($('<a/>',click : function(e){
- e.preventDefault();
- $('#' + child).remove();
- }
- }));
解决方法
您可以使用
.appendTo()
追加第一个< div>到具有ID容器的元素,以便您具有对该新元素的引用,然后使用.append():
- $('<div/>',{
- 'id' : 'child'
- }).appendTo('#container').append(
- $('<a/>',{
- 'class' : 'close',click : function(e){
- e.preventDefault();
- $('#' + child).remove();
- }
- })
- );