Sono molto confuso sul motivo per cui solo l'ultimo elemento viene inserito quando tento di aggiungere più elementi all'interno di un ciclo for.Come inserire più elementi in un elemento tramite append in un ciclo for?
Ho creato uno JsFiddle che mostra la mia impossibilità di farlo funzionare. Mi aspetto di inserire 100 tag di ancoraggio, ma è inserito solo l'ultimo elemento.
Per l'amor del posteriore, ecco il relativo JavaScript, il TODO segna la parte rilevante:
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);
});
voglio inserire tutti i 100 elementi in div.door_game
:
<body>
<h1>Zonk!</h1>
<div class="door_game" data-doors="10">
</div>
</body>
probabilmente è necessario modificare 'Math.round (Math.random() * 100% 100)' a 'Math.round (Math.random() * max% max)' – razzak
@razzak Sì, ho notato anche questo mentre preparavo la domanda, non era necessario risolvere il problema reale. Grazie per avermelo fatto notare comunque. – k0pernikus
anche questo non ha senso 'this.doors [this.jackpotNumber] .containsZonk = true;' quando tutti gli oggetti 'door' hanno questa proprietà' containsZonk: true, '! potresti voler cambiarlo in 'cotainsZonk: false,'? – razzak