2012-05-02 86 views
13

我有以下jQuery代码的工作原理,但它让我思考,如果有可能对附加内容做追加动作而不需要指定我想追加的内容。 append().append()没有做到这一招,它只是把这两个元素相互靠近,而不是第一个append()行动的孩子。jQuery附加在附加元素

作品:

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'), 
    child = 'child'; 

$('#container').append($('<div/>',{ 
    'id' : 'child' 
})).append($('<a/>', { 
    'class' : 'close', 
    'href' : 'javascript:;', 
    html : 'close', 
    click : function(e){ 
     e.preventDefault(); 
     $('#' + child).remove(); 
    } 
})); 

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

回答

17

您可以使用.appendTo()到第一<div>追加到ID为容器的元素,让你有新的元素的引用,然后使用.append()

$('<div/>',{ 
    'id' : 'child' 
}).appendTo('#container').append(
    $('<a/>', { 
     'class' : 'close', 
     'href' : 'javascript:;', 
     html : 'close', 
     click : function(e){ 
      e.preventDefault(); 
      $('#' + child).remove(); 
     } 
    }) 
); 
1

我会用appendto然后追加 http://jsfiddle.net/Y8TwW/2/

var container = $('#container'), 
    child = 'child'; 
$('<div/>', { 'id': child } 
).appendTo(container 
).append($('<a/>', { 
    'class' : 'close', 
    'href' : 'javascript:;', 
    html : 'close', 
    click : function(e){ 
     e.preventDefault(); 
     $('#' + child).remove(); 
    } 
})); 
+1

将相关代码的答案,而不仅仅是一个链接到小提琴。 – Gabe

2

因为append不返回参照所附内容。它指的是第一次追加后的相同对象,即container,或者不管您要运行多少次追加。正如其他建议使用appendto或者您可以使用以下更好地说明为什么你失败。

var container = $('#container'), 
    child = 'child'; 

    $('#container').append($('<div/>',{ 
     'id' : 'child' 
     })).find('#' + child).append($('<a/>', { 
     'class' : 'close', 
     'href' : 'javascript:;', 
     html : 'close', 
     click : function(e){ 
      e.preventDefault(); 
      $('#' + child).remove(); 
     } 
    }));​ 

小提琴http://jsfiddle.net/Y8TwW/3/