jQuery的追加附加元素中 [英] jQuery append inside appended element

查看:140
本文介绍了jQuery的追加附加元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的jQuery code这工作,但它让我深思,如果它是可能做什么被追加,而无需指定什么,我想追加到的追加措施。 追加()。追加()并没有这样的伎俩,它只是把两个元素彼此相邻,而不是第一个孩子追加()操作。

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 I wanted to append to. append().append() didn't do the trick, it just put the two elements next to each other and not a child of the first append() action.

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/

推荐答案

您可以使用 .appendTo() 第一个追加&LT; D​​IV&GT; 与ID容器中的元素,让你有一个参考,以新的元素,那么使用 .append()

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

这篇关于jQuery的追加附加元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆