简体   繁体   中英

How to insert HTML dynamically on php generated content

I have a php file that dynamically loads in images from the server, 20 images at one time, kind of like how Facebook's wall posts get dynamically loaded to the page when the user scrolls down.

What I want to do is squeeze in custom content before every 9th item, starting from the 4th item.

I tried manipulating the DOM with jQuery's insertBefore() method ie

var length = $('#container .item').length();
var i = 11;

while (i < length) {
    var el = $('#container .item').eq(i);
    $('<div>custom content</div>').insertBefore(el);
    i += 9;
}

This works fine on the initially loaded content, but not on the content that are dynamically loaded in from the server.

I would like to ask: 1) Is there any way to manipulate the DOM on a dynamically loaded content? (using .bind perhaps?) 2) If not, what method should I take about?

It's definitely possible to do this, but you need to think carefully how this all fits together.

As I understand, you have a php page that serves the user "initial" content (like when you simply open up facebook the first time). Once the page is loaded you add custom content through javascript/jQuery code (here I assume your custom content is not coming from php code).

On certain user interaction (or otherwise) you want to load new, dynamic content (such as scrolling further down on facebook for example). An ajax request is sent, a callback is made and this custom content is appended to (or replaces other content on) the page. At this point you need to re-run the code on the client that added the custom content onto your page initially.

note that if this custom content is also delivered by your server, you need to provide the custom content that goes with the other dynamically loaded content in the same, or a new, callback.

So to summarize:

  1. initial page load from PHP file (server side)
  2. JS/jQuery code adds custom content (client side)
  3. Event (such as user interaction) for more dynamic content occurs, ajax request is sent (client side)
  4. PHP retrieves and returns more dynamic content (server side)
  5. Ajax request succeeds and has this new content, it gets appended to the page (client side)
  6. More custom content needs to be added, by JS/jQuery (client side)

That's roughly the "flow" behind a webpage with dynamic content, to give a concrete solution for you however, we need to see more of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM