简体   繁体   English

在DOM中附加动态(新创建)的元素

[英]Append a dynamicaly (newly) created element in DOM

I'm trying to append an element dynamically in a recursive manner, ie : 我试图以递归的方式动态地添加元素,即:

I have an anchor tag with class "request-get", onclick of this anchor tag I append a div with several anchor tags having the same class name "request-get" and divs to append when clicking on the last created anchor tags : here's my code 我有一个带有“ request-get”类的锚标签,此锚标签的onclick我在一个div上附加了几个具有相同类名“ request-get”的锚标签,并在单击最后创建的锚标签时附加div:这是我的密码

NB : The ajax call works fine, I get all the data after click event of the newly created anchor tags but I don't get the reference of the newly created Divs 注意:ajax调用工作正常,我在获得新创建的锚标记的click事件后获得了所有数据,但没有获得新创建的Divs的引用

$(document).on("click", ".request-get", function (event) {
    var request = new RequestModule.AjaxRequestBuilder(this).build();
    var child = $(this).data('target');
    var childDocument = $(document).find(child);
    console.log(childDocument);
    request.call({
        success: function (response) {
            $(child).empty();
            console.log($(child));
            for (var i in response) {

                var a = $('<a/>', { href: "" })
                            .attr('id', response[i].code)
                            .attr('class', 'request-get child')
                            .attr('data-id', response[i].id)
                            .attr('data-controller', 'objectif')
                            .attr('data-controller-suffix', 'children')
                            .attr('data-method', 'get')
                            .attr('data-target', '#details_' + response[i].code)
                            .attr('data-toggle', 'collapse')
                            .css('display', 'block')
                            .text(response[i].code+' - '+response[i].intitule);

                var div = $('<div/>', { id: 'details_' + response[i].code })
                            .attr('class', 'details collapse child');


                $(child).append(a);
                $(child).append(div);

            }
        },

        error: function (response) {

        }
    });
});

我认为您可能使用了错误的变量,因为您正在使用child变量而不是childElement

Your newly append elements don't have same class. 您新添加的元素没有相同的类。 You are providing "request-get-objectif" instead of "request-get" 您正在提供“ request-get-objectif”而不是“ request-get”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM