jQuery附加在附加元素中

前端之家收集整理的这篇文章主要介绍了jQuery附加在附加元素中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下jQuery代码可以工作,但它让我思考,如果有可能对附加的内容执行追加操作,而无需指定我想要追加的内容. append().append()没有做到这一点,它只是将两个元素放在一起,而不是第一个append()动作的子元素.

作品:

  1. var container = $('#container'),child = 'child';
  2.  
  3. $('#container').append($('<div/>',{
  4. 'id' : 'child'
  5. }));
  6.  
  7. $('#' + child).append($('<a/>',{
  8. 'class' : 'close','href' : 'javascript:;',html : 'close',click : function(e){
  9. e.preventDefault();
  10. $('#' + child).remove();
  11. }
  12. }));

不起作用:

  1. var container = $('#container'),{
  2. 'id' : 'child'
  3. })).append($('<a/>',click : function(e){
  4. e.preventDefault();
  5. $('#' + child).remove();
  6. }
  7. }));

http://jsfiddle.net/Y8TwW/1/

解决方法

您可以使用 .appendTo()追加第一个< div>到具有ID容器的元素,以便您具有对该新元素的引用,然后使用.append():
  1. $('<div/>',{
  2. 'id' : 'child'
  3. }).appendTo('#container').append(
  4. $('<a/>',{
  5. 'class' : 'close',click : function(e){
  6. e.preventDefault();
  7. $('#' + child).remove();
  8. }
  9. })
  10. );

猜你在找的jQuery相关文章