jQuery append inside appended element

后端 未结 3 1436
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 19:09

I have the following jQuery code which works, but it made me ponder if it were possible to do an append action on what was being appended without the need of specifying what

相关标签:
3条回答
  • 2020-12-15 19:23

    I'd use the appendto and then append 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();
        }
    }));
    
    0 讨论(0)
  • 2020-12-15 19:28

    You can use .appendTo() to append the first <div> to the element with ID container, so that you have a reference to that new element, then use .append():

    $('<div/>',{
        'id'    : 'child'
    }).appendTo('#container').append(
        $('<a/>', {
            'class' : 'close',
            'href'  : 'javascript:;',
            html    : 'close',
            click   : function(e){
                e.preventDefault();
                $('#' + child).remove();
            }
        })
    );
    
    0 讨论(0)
  • 2020-12-15 19:30

    Because append doesn't return reference to the appended content. It is referring to the same object i.e. container after the first append, or no matter how many appends you would run. So as other suggested use appendto or you can use the following that better demonstrate why you were failing.

        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();
             }
        }));​
    

    Fiddle http://jsfiddle.net/Y8TwW/3/

    0 讨论(0)
提交回复
热议问题