Irsyad14 Irsyad14 - 17 days ago 8
jQuery Question

jQuery append inside for loop

I have a particular problem which I dont seem to wrap around my head. I am using reddit api to get the data.

UPDATED

$(function() {

console.log("is it loading")

axios.get('http://www.reddit.com/r/DrunkOrAKid/hot.json?sort=hot')
.then(function(data){
var q;
for(var i = 2; i < data.data.data.children.length; i++){
q = data.data.data.children[i];
$('#main').append('<h4>' + q.data.title + '</h4><br><button class="btn btn-success trigger">answer</button><div class="answer">'+ q.data.selftext +'</div>')


$('.answer').hide()


$('.trigger').click(function(e){
e.preventDefault()
console.log("clicked", [i]);
$('.answer').show()
})
}
}).catch(function(error){
console.log("error occured")
})
})


So basically I wanted to show the answer using #trigger. But the problem lies when I clicked the #trigger button, the array shows 27 count rather than the actual count which is 26. It somehow added one count when I click #trigger button. Right now I cannot managed to click the button to show the answer. Any help would be much appreciated

Answer

Try this and see. It's not doing lookups. It's using/bind on the elements as it makes them. A better approach might be to use a delegated listener with contextual lookups.

    axios.get('http://www.reddit.com/r/DrunkOrAKid/hot.json?sort=hot')
        .then(function(data) {
            var $main = $('#main');

            //use slice so you can use forEach instead of rolling your own for loop
            data.data.data.children.slice(2).forEach(function(child){
                //instead of looking up trigger, create it so you can do whatever you want with it
                var $trigger = $('<button class="btn btn-success">answer</button>');
                //same with answer
                var $answer = $('<div class="answer">'+ child.data.selftext +'</div>');

                $answer.hide();

                $trigger.on('click', function(e){
                    e.preventDefault();
                    $answer.show();
                });

                $main
                    .append('<h4>'+ child.data.title +'</h4><br>')
                    .append($trigger)
                    .append($answer);
            });
        }).catch(function(error) {
            console.log("error occured")
        });
    });