jquery load more content onclick

2019-07-28 09:09发布

问题:

This is what I have so far:

$(document).ready(function(){   
  $("#feed-page").load("feed.php #first-feed");

  $('.feed-load').click(function(){   
    $("#feed-page").load("feed.php #second-feed" ,  hideLoading);
    $(".feed-load .button-content").css( "display" , "none" );
    $('.feed-load-img').css( "display" , "block" );
  });

  function hideLoading() {  
    $(".feed-load .button-content").css( "display" , "block" );
    $(".feed-load .feed-load-img").css( "display" , "none" ); 
  }
}); // end document ready

My problem is that when I click on "load more" what happens is that the content gets swapped out.

That is not what I want to happen, I just want the content to all stay meaning the content that is already there on page load I want that to stay however when I click on "load more" I would like that content to stay but for some reason the content that was originally there gets swapped out with the new content which I don't want to happen.

A live example can be found here: http://www.cyberfanatic.com

回答1:

The issue with your current code is that after the user clicks the button, you are loading the new data over the existent one. See jQuery .load().

What you need is to append the new data, in order to preserve the existent one:

// on click
$('.feed-load').click(function(){   

  // load the new data to an element
  $("<div>").load("feed.php #second-feed", function() {

    // all done, append the data to the '#feed-page'
    $("#feed-page").append($(this).find("#second-feed").html());

    // call your function
    hideLoading();
  });

  // continue the remaining of your code...
  $(".feed-load .button-content").css( "display" , "none" );
  $('.feed-load-img').css( "display" , "block" );
});

EDITED

Append with some animation as requested at the comment:

...
// all done, append the data to the '#feed-page'
var $html   = $(this).find("#second-feed").html(),
    $newEle = $('<div id="second-feed" />').attr("style", 'display:none;').html($html);

$("#feed-page").append($newEle);
$('#second-feed').slideToggle();
...

See this Fiddle Example!