Can jQuery .load append instead of replace?

2019-01-11 11:02发布

问题:

I have a WordPress install and I'm trying to use jQuery to create a Load More effect. I'm having some trouble using the basic .load feature for page fragments. I don't mind using .get as I saw some threads here regarding that as a better solution.

Here's my page URL structure and the contents:

First Page: http://example.com/page/1/

The HTML:

<div id="articles">
  <div class="story">blah blah blah</div>
  <div class="story">blah blah blah</div>
  <div class="story">blah blah blah</div>
  <div class="story">blah blah blah</div>
</div>

Second Page: http://example.com/page/2/

The HTML:

<div id="articles">
  <div class="story">blah blah blah</div>
  <div class="story">blah blah blah</div>
  <div class="story">blah blah blah</div>
  <div class="story">blah blah blah</div>
</div>

I have a link at the bottom of the page and I've tried doing the following:

jQuery(#articles).load('http://example.com/page/2/ #articles');

Sadly, there are 2 issues. First the .load function grabs the #articles div and its contents from the second page and places it into the existing #articles div. That means, even if this were to work, there would be recursive divs within divs resulting from each click. It's just messy.

Could someone help me with the command to simply append the .story classes from the second page into the #articles div on the first page? I can figure out the logistics of automating it with variables, loops, and PHP for WordPress after. Just need some assitance with the proper jQuery script.

P.S. Bonus Question: If anyone knows whether jQuery .load/.get will harm pageviews, which is important for those with advertising-based revenue, please let me know! If each .load/.get counts as another hit for Google Analytics, we're good!

Thanks!

回答1:

You can't append content using the jQuery.load() method, but you can do what you want using jQuery.get():

$.get('/page/2/', function(data){ 
  $(data).find("#articles .story").appendTo("#articles");
});


回答2:

I'd probably do it like this.

$('#articles').append($('<div/>', { id: '#articles-page2' });
$('#articles-page2').load('http://example.com/page/2/ #articles > *');

#articles > * fetches all immediate children to #article.



回答3:

For appending data, I don't think you would want to use $.load(). Instead, you might want to look into using $.ajax().

$.ajax({
  url: 'yourlocation/test.html',
  success: function(data) {
    $('.result').html(data);
    $("#yourdiv").append(data);
  }
});


回答4:

Try this it worked for me.

$('#articles').append( $('<div/>').load('http://example.com/page/2/ #articles') );