如何使用JavaScript而不是jQuery动态填充JSON数据的html元素? [英] How do I dynamically populate html elements with JSON Data with Javascript not jQuery?
本文介绍了如何使用JavaScript而不是jQuery动态填充JSON数据的html元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下JSON数据snippit:
{items:[
{
title:sample 1,
author:author 1
},
{
title:sample 2,
作者:作者2
}
]}
我如何使用此数据填充以下html元素:
< div class =news-story>
< h5>样品1< / h5>
< p> By:author 1< / p>
< h5>样本2< / h5>
< p> By:author 2< / p>
< / div>
我想用Javascript而不是jQuery完成此操作。 通过循环并使用 DOM 函数:
var news = document.getElementsByClassName(news-story) [0];
var items = json.items;
for(var i = 0; i< items.length; i ++){
var h5 = document.createElement(h5);
h5.innerHTML = items [i] .title;
news.appendChild(h5);
var p = document.createElement(p);
p.innerHTML = items [i] .author;
news.appendChild(p);
}
$ b
getElementsByClassName
在9之前的IE版本中不起作用。如果你需要支持这些,你最好使用jQuery。
I have this following JSON data snippit:
{"items": [
{
"title": "sample 1",
"author": "author 1"
},
{
"title": "sample 2",
"author": "author 2"
}
]}
How do I populate the following html elements with this data:
<div class="news-story">
<h5>sample 1</h5>
<p>By: author 1</p>
<h5>sample 2</h5>
<p>By: author 2</p>
</div>
I want accomplish this with Javascript not jQuery.
解决方案
Loop through them and use the DOM functions:
var news = document.getElementsByClassName("news-story")[0];
var items = json.items;
for(var i = 0; i < items.length; i++) {
var h5 = document.createElement("h5");
h5.innerHTML = items[i].title;
news.appendChild(h5);
var p = document.createElement("p");
p.innerHTML = items[i].author;
news.appendChild(p);
}
getElementsByClassName
will not work in versions of IE prior to 9. If you need to support those though, you're really better off using jQuery.
这篇关于如何使用JavaScript而不是jQuery动态填充JSON数据的html元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文