0
votes

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?

2
Please add your Codedk1990
@Noah sorry forgot that, have updated.user4913383
No, append wont avoid duplicating content:enno.void
you're avoiding it yourself with the $(".text").text(""); that you call every time on the success call.LordNeo

2 Answers

4
votes

that's because you do this:

$(".text").text("");

When you do that it empties the div every time you click the button.

1
votes

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 + '"/>');
        }
      }