Can jQuery .load append instead of replace?

2019-01-11 11:14发布

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!

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-11 11:30

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);
  }
});
查看更多
家丑人穷心不美
3楼-- · 2019-01-11 11:35

Try this it worked for me.

$('#articles').append( $('<div/>').load('http://example.com/page/2/ #articles') );
查看更多
趁早两清
4楼-- · 2019-01-11 11:38

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");
});
查看更多
闹够了就滚
5楼-- · 2019-01-11 11:51

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.

查看更多
登录 后发表回答