Reputation: 171
In this example I am loading JSON data from reddit using ajax. As the response comes from server I append it to div with a class .text
.
<button type="button" class="btn">Click me!</button>
<div class="text">Replace me!!</div>
$(".btn").click(function () {
$.ajax({
url: "http://www.reddit.com/r/aww/search.json?q=puppy&restrict_sr=true",
method: "GET",
success: function (result) {
$(".text").text("");
for (var i = 0; i < result.data.children.length; i++) {
$(".text").append('<img src="' + result.data.children[i].data.thumbnail + '"/>');
}
}
});
});
This works. My question is why does append function not append same images again as I press button repeatedly? Does append function avoid duplicating content somehow?
Upvotes: 0
Views: 60
Reputation: 309
You deleted the element everytime by clicking because of $(".text").text(""); If you add an element like i did you can replace the text with nothing and show the elements in a new div.
If you use your code like this the text will be gone and the pictures will be there.
HTML:
<button type="button" class="btn">Click me!</button>
<div class="text">Replace me!!</div>
<div class="images"> </div>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
JS
// Attach a button listener to the button
//
$(".btn").click(function(){
$.ajax({
url: "http://www.reddit.com/r/aww/search.json?q=puppy&restrict_sr=true",
method: "GET",
success: function(result){
$('.text').html('')
for(var i=0; i < result.data.children.length ; i++){
$(".images").append('<img src="' + result.data.children[i].data.thumbnail + '"/>');
}
}
Upvotes: 1
Reputation: 792
that's because you do this:
$(".text").text("");
When you do that it empties the div every time you click the button.
Upvotes: 4