How to insert multiple elements into one element via append in a for loop?

I am very confused why only the last element is inserted when I try to add multiple elements to the for loop.

I created a JsFiddle , demonstrating my inability to make it work. I expect 100 anchor tags to be inserted, but only the last element is inserted.


For future reference, here is the relevant JavaScript, TODO marks the relevant part:
Math.randomNumber = function(max) {
    return Math.round(Math.random() * max % max);
}


var Door = {
    $el: $('<a>', {
        class: 'door selectable'
    }),
    number: null,
    isSelected: false,
    containsZonk: true,
    bind: function () {
        var that = this;
        this.$el.on('click tap', function () {
            that.isSelected = true
        });
    }
}

var Platform = {
    $el: null,
    doorCount: null,
    jackpotNumber: null,
    doors: [],
    init: function($el, doorCount) {
        this.$el = $el;
        this.doorCount = doorCount;

        for (var i = 0; i <= doorCount - 1; i++) {
            var door = Object.create(Door);
            door.number = i;
            door.$el.html(i.toString());
            this.doors.push(door);

            /* TODO: wtf why is only last one inserted? */
            this.$el.append(door.$el);
        }

        this.jackpotNumber = Math.randomNumber(doorCount);
        this.doors[this.jackpotNumber].containsZonk = false;
    }
}
    $(document).ready(function(){
        var platform = Object.create(Platform);
        var $game = $('.door_game');
        platform.init($game, 100);
    });

I want to insert all 100 elements in div.door_game:

<body>
    <h1>Zonk!</h1>
        <div class="door_game" data-doors="10">
        </div>
</body>
+5
source share
2 answers

This is because all of your doors have the same $el.

http://jsfiddle.net/U9swZ/9/

var Door = {
    number: null,
    isSelected: false,
    containsZonk: true,
    bind: function () {
        var that = this;
        this.$el.on('click tap', function () {
            that.isSelected = true
        });
    },
    init: function () {
        this.$el = $('<a>', {
            class: 'door selectable'
        });
        return this;
    }
}
+6
source

$el (.. ), . @plalx .

, , , documentFragment (var frag = document.createDocumentFragment()) , (frag.appendChild(...)) Fragment $el (this.$el.appendChild(frag)). .

, , . . DOM API cloneNode(false), .

+2

All Articles