简体   繁体   中英

How do I dynamically append a large block of HTML to a div?

I'm trying to learn web development, so I don't have much experience with the various languages and markups yet. I'm making a website with a blog that reads JSON data from the Tumblr v2 API. After getting the JSON data from Tumblr I want to add some of the data from each post to my own website's blog, here's the code that I've been trying to use..

<script>
function loadBlogPosts(){
$.getJSON("http://api.tumblr.com/v2/blog/[MY_BLOG]/info?api_key=[MY_KEY]",
    function(blogData){
        $.each(blogData.posts, function(){
             $(#main_content).append( [BUNCH OF NESTED HTML] );
        });
    }
);
}
</script>

Before writing this, I thought it would be a good idea to make a 'layout' of each blog post in divs. So i came up with this:

<div class="post">
    <div class="post_header">
        <div class="post_title"></div>
        <div class="post_author"></div>
        <div class="post_date"></div>
    </div>
    <div class="post_content"></div>
    <div class="post_footer"></div>
</div>

But that's where I'm stuck. I know what I want to do, but I don't have enough experience with JavaScript/JQuery/JSON/HTML to know how to do it. I want parse the JSON blog data and, for each post, take the post content and apply it to that div structure while writing/appending it to the "main_content" div.. I tried copy-pasting that group of divs into the append function surrounded by quotes, but it became a real mess of quotes and slashes, and it didn't look like it was working correctly..

So, whats the best way for me to do that? Is there a good way of applying a big chunk of nested HTML elements while populating them with content from my JSON data? If not, what should I do? I'm still very new to HTML, JavaScript, and web coding in general, so I may be going about this completely wrong!

when you want to do everything with jquery yoiu could use something like this:

var post = $('<div class="post"></div>');
var postheader = $('<div class="post_header"></div>');

postheader.append('<div class="post_title"></div>');
postheader.append('<div class="post_author"></div>');

post.append(postheader);
post.append('<div class="post_content"></div>');
post.find('.post_title').text('my title');
post.find('.post_content').text('my content');

$('#main_content').append(post);

instead of .text('my title') you can use .text(variable) of course

If you want HIGH PERFORMANCE:

In pure javascript the highest performing method is probably using createDocumentFragment()

function postEl(json){ // create a function for the POST element
 var post=document.createElement('div');
 post.className='post';
 var postHeader=document.createElement('div');
 postHeader.className='post_header';
 var postTitle=document.createElement('div');
 postTitle.className='post_title';
 postTitle.tectContent=json.title;
 //more code
 postHeader.appendChild(postTitle);
 //more code
 post.appendChild(postHeader);
 return post;
}

function appendPosts(){ // append each post to a fragment. and then to the main
 var frag=document.createDocumentFragment();
 for(/*each post*/){
  frag.appendChild(postEl(/*jsonPost*/));
 }
 document.getElementById('main_content').appendChild(frag);
}

Precreating the structure should also increase the performance.

cloneNode

https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode

https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment

cloning the node also increases the performance by setting the valuse directly without recreating each individual node.

function appendPosts(js){
 var node=document.createElemtnt('div'),
 frag=document.createDocumentFragment();
 node.innerHTML='<div class="post_header"><div class="post_title"></div><div class="post_author"></div><div class="post_date"></div></div><div class="post_content"></div><div class="post_footer"></div>';
 for(var a=0,b;b=js.posts[a];++a){
  var newNode=node.cloneNode(true),
  childs=newNode.childNodes,
  header=childs[0].childNodes;
  header[0].textContent=b.title/*title from Postdata*/;
  header[1].textContent=b.author/*author from Postdata*/;
  header[2].textContent=b.date/*date from Postdata*/;
  childs[1].textContent=b.content/*content from Postdata*/;
  childs[2].textContent=b.footer/*footer from Postdata*/;
  frag.appendChild(newNode);
 }
 document.getElementById('main_content').appendChild(frag);
}

function loadBlogPosts(){
 $.getJSON("http://api.tumblr.com/v2/blog/[MY_BLOG]/info?api_key=[MY_KEY]",
 appendPosts
)

This function should work now .. but as i don't exactly know the json response you may need to change the various post keys.

note: i put the fragment thing in a function so you have an idea how it works. you should put the postEl content inside the appendPosts function... (thats also faster)

if you have any questions just ask.

EDIT

no they are not globals

var a,b,c,d; // not globals == var a;var b;var c;var d;
var a,b;c;d; // c d = gobal
// , comma affter a var allows you to not write 1000 times var.

EDIT2

 //.......
  frag.appendChild(newNode);
 }
 var topNode=document.createElement('div');
 topNode.className='post';
 topNode.appendChild(frag);
 document.getElementById('main_content').appendChild(topNode);
 //.....

you could do something like this:

$.each(blogData.posts, function(i,v){
    var cnt= '<div class="post">' +
             '<div class="post_header">' +
                     '<div class="post_title">'+ blogData.posts[i].title +'</div>' +
                     '<div class="post_author">'+ blogData.posts[i].author +'</div>' +
                     '<div class="post_date">'+ blogData.posts[i].date +'</div>' +
             '</div>' +
             '<div class="post_content">' +
                 blogData.posts[i].body +
             '</div>' +
             '<div class="post_footer">' +
             '</div>' +
         '</div>';
    $('#main_content').append(cnt);
});

Note that you don't need to split up all the lines, i've just done that to make it more readable. (I'm also not sure if all the variables are correct, (i don't think author exists) but it's just as a demo)

Write your code in a separate page, then append a whole html page into a div by using:

$('#containerDiv').load('page.htm');

Also, this is a good way to fragment the content.

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