简体   繁体   中英

Nested dynamically added content

I'm creating a form which allows the users to add additional content on the fly. The structure of the form is such that there are three dimensions to the form data, ie, like a movie can play at different theatres and each theatre can have different showing times. The form, therefore has grandparent, parent and child divs, and the parent & child divs can be added to on the press of a button.

Here's a slimed-down version of the code for clarity

<div id="grandparent">
    <div id="parent">
        Parent 1
        <div id="child">
            Child 1
        </div>       
    </div>
    <button id="addChild">Add Child</button>
</div>
<button id="addParent">Add Parent</button>

<script>
$(function() {
var grandparent_div = $('#grandparent');
    var parent_div = $('#parent');
    var child_div = $('#child');
    var p = $('#grandparent div#parent').size() + 1;
    var c = $('#parent div#child').size() + 1;
    $('#addChild').on('click', function() {
        $('<div id="child">Child '+c+'</div>').appendTo(parent_div);
    });
    $('#addParent').on('click', function() {
        $('<div id="parent">Parent '+p+'<div id="child">Child 1</div><button id="addChild">Add Child</button></div>').appendTo(grandparent_div);
    });
});
</script>

JSFiddle here: http://jsfiddle.net/u2vUT/

I can create parent nodes fine, and I can even create child nodes of parents on the first level - the problem comes when trying to add children of dynamically-added parents. It's probably because the 'addChild' button is no longer unique, so $('#addChild').on('click') can't reference it. So, is there a way to make this work (preferably elegant!)?

You should not use ids, use class

<div id="grandparent">
    <div class="parent">Parent 1
        <div class="child">Child 1</div>
    </div>
    <button class="addChild">Add Child</button>
</div>
<button id="addParent">Add Parent</button>

then

$(function () {
    var grandparent_div = $('#grandparent');
    var parent_div = $('.parent');
    var child_div = $('.child');
    var p = grandparent_div.find('.parent').size() + 1;

    grandparent_div.on('click', '.addChild', function () {
        $('<div id="child">Child ' + ($(this).siblings().length + 1) + '</div>').insertBefore(this);
    });
    $('#addParent').on('click', function () {
        $('<div class="parent">Parent ' + p + '<div class="child">Child 1</div><button class="addChild">Add Child</button></div>').appendTo(grandparent_div);
    });
});

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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