如何通过在for循环中附加多个元素到一个元素中?

时间:2021-07-09 19:55:36

I am very confused as to why only the last element is inserted when I try to append multiple elements within a for loop.

当我试图在for循环中附加多个元素时,为什么只插入最后一个元素,我感到非常困惑。

I have created a JsFiddle showcasing my inability to get it to work. I expect 100 anchor tags to be inserted, yet only the last element is inserted.

我创建了一个JsFiddle,它表示我无法使它工作。我希望插入100个锚标记,但只插入最后一个元素。


For posterior's sake, here's the relevant JavaScript, the 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 into div.door_game:

我想将所有100个元素插入div。door_game:

<body>
    <h1>Zonk!</h1>
        <div class="door_game" data-doors="10">
        </div>
</body>

2 个解决方案

#1


6  

It's because all your doors are sharing the same $el.

这是因为你所有的门都共享同样的el。

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

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

#2


2  

The Door $el is created once and that's why it is appended and appended again (i.e. moved again and again) so that you only see the last one. @plalx is right about it.

$el的门被创建了一次,这就是为什么它被追加和追加(例如,一次又一次地移动),所以你只能看到最后一个。@plalx是对的。

Morever, something very important since you append hundreds of doors, use a documentFragment (var frag = document.createDocumentFragment()) before the loop, to gather you doors (frag.appendChild(...)) and append this documentFragment to the Platform $el after the loop (this.$el.appendChild(frag)). The performance gain is very important with such amounts of elements.

更重要的是,由于您附加了数百个门,所以在循环之前使用一个documentFragment (var frag = document.createDocumentFragment()),收集doors (frag.appendChild(…)),并在循环之后将这个documentFragment (this.$el.appendChild(frag))添加到$el平台。在这些元素的数量上,性能增益是非常重要的。

And, don't hesitate to clone an element instead of rebuilding it. It 's much more faster. You can even use the DOM API cloneNode(false) method to do a not in depth copy of the original element.

不要犹豫克隆一个元素而不是重建它。它要快得多。您甚至可以使用DOM API cloneNode(false)方法对原始元素进行非深度复制。

#1


6  

It's because all your doors are sharing the same $el.

这是因为你所有的门都共享同样的el。

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

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

#2


2  

The Door $el is created once and that's why it is appended and appended again (i.e. moved again and again) so that you only see the last one. @plalx is right about it.

$el的门被创建了一次,这就是为什么它被追加和追加(例如,一次又一次地移动),所以你只能看到最后一个。@plalx是对的。

Morever, something very important since you append hundreds of doors, use a documentFragment (var frag = document.createDocumentFragment()) before the loop, to gather you doors (frag.appendChild(...)) and append this documentFragment to the Platform $el after the loop (this.$el.appendChild(frag)). The performance gain is very important with such amounts of elements.

更重要的是,由于您附加了数百个门,所以在循环之前使用一个documentFragment (var frag = document.createDocumentFragment()),收集doors (frag.appendChild(…)),并在循环之后将这个documentFragment (this.$el.appendChild(frag))添加到$el平台。在这些元素的数量上,性能增益是非常重要的。

And, don't hesitate to clone an element instead of rebuilding it. It 's much more faster. You can even use the DOM API cloneNode(false) method to do a not in depth copy of the original element.

不要犹豫克隆一个元素而不是重建它。它要快得多。您甚至可以使用DOM API cloneNode(false)方法对原始元素进行非深度复制。