jQuery 在附加元素内追加 [英] jQuery append inside appended element

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

问题描述

我有以下有效的 jQuery 代码,但它让我思考是否可以对所附加的内容执行附加操作,而无需指定我想要附加的内容.append().append() 没有解决问题,它只是将两个元素并排放置,而不是第一个 append() 操作的子元素.

作品:

var container = $('#container'),孩子 = '孩子';$('#container').append($('<div/>',{'id':'孩子'}));$('#' + child).append($('<a/>', {'类':'关闭','href' : 'javascript:;',html : '关闭',点击:功能(e){e.preventDefault();$('#' + child).remove();}}));

不起作用:

var container = $('#container'),孩子 = '孩子';$('#container').append($('<div/>',{'id':'孩子'})).append($('<a/>', {'类':'关闭','href' : 'javascript:;',html : '关闭',点击:功能(e){e.preventDefault();$('#' + child).remove();}}));

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

解决方案

您可以使用 .appendTo() 将第一个

附加到具有 ID 容器的元素,以便您可以引用该新元素,然后使用 .append():

$('

',{'id':'孩子'}).appendTo('#container').append($('<a/>', {'类':'关闭','href' : 'javascript:;',html : '关闭',点击:功能(e){e.preventDefault();$('#' + child).remove();}}));

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.

Works:

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

Does Not Work:

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/

解决方案

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天全站免登陆