如何使用 Javascript 而不是 jQuery 使用 JSON 数据动态填充 html 元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8314712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I dynamically populate html elements with JSON Data with Javascript not jQuery?
提问by Amen Ra
I have this following JSON data snippit:
我有以下 JSON 数据片段:
{"items": [
{
"title": "sample 1",
"author": "author 1"
},
{
"title": "sample 2",
"author": "author 2"
}
]}
How do I populate the following html elements with this data:
如何使用此数据填充以下 html 元素:
<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.
我想用 Javascript 而不是 jQuery 来完成这个。
回答by Alex Turpin
Loop through them and use the DOMfunctions:
循环遍历它们并使用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);
}
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.
getElementsByClassName
在 9 之前的 IE 版本中将无法工作。如果您需要支持这些,则最好使用 jQuery。
回答by RightSaidFred
var div = document.getElementsByClassName('news-story')[0],
h5 = div.getElementsByTagName('h5'),
p = div.getElementsByTagName('p'),
data = JSON.parse( my_JSON_data );
data.items.forEach(function(v,i) {
h5[i].innerHTML = v.title;
p[i].innerHTML = "By: " + v.author;
});
If you need to support older browsers, you can use a typical for
statement instead of the forEach
method.
如果需要支持旧版浏览器,可以使用典型for
语句代替forEach
方法。
for( var i = 0; i < data.items.length; ++i ) {
var v = data.items[i];
h5[i].innerHTML = v.title;
p[i].innerHTML = "By: " + v.author;
}
And I'd suggest using an ID instead of a class for the news-story
element, so you can use getElementById
instead (unless of course you have several of them).
而且我建议使用一个ID,而不是为一类news-story
元素,这样你就可以使用getElementById
,而不是(当然,除非你有几个)。
If that's impossible, you may want to use a compatibility function from MDNfor getElementsByClassName
.
如果这是不可能的,您可能需要使用MDN 中的兼容性功能来实现getElementsByClassName
.
If you needed to create the inner elements, then here's one way:
如果您需要创建内部元素,那么这是一种方法:
var div = document.getElementsByClassName('news-story')[0],
data = JSON.parse( my_JSON_data ),
html;
html = data.items.map(function(v,i) {
return '<h5>' + v.title + '</h5>' +
'<p>By: ' + v.author + '</p>';
}).join('');
div.innerHTML = html;
@Xeon06 shows how in his answer using createElement()
, which is arguably a better approach.
@Xeon06 在他的回答中展示了如何使用createElement()
,这可以说是一种更好的方法。
Here's how I'd do it:
这是我的做法:
var div = document.getElementsByClassName('news-story')[0],
frag = document.createDocumentFragment(),
data = JSON.parse( my_JSON_data );
data.items.forEach(function(v,i) {
frag.appendChild( document.createElement('h5') ).innerHTML = v.title;
frag.appendChild( document.createElement('p') ).innerHTML = "By: " + v.author;
});
div.appendChild( frag );
And of course you can modify it to use a for
statement instead:
当然,您可以修改它以使用for
语句:
var div = document.getElementsByClassName('news-story')[0],
frag = document.createDocumentFragment(),
data = JSON.parse( my_JSON_data );
for( var i = 0; i < data.items.length; ++i ) {
var v = data.items[i];
frag.appendChild( document.createElement('h5') ).innerHTML = v.title;
frag.appendChild( document.createElement('p') ).innerHTML = "By: " + v.author;
}
div.appendChild( frag );
The benefit of using a documentFragment
is that you can do a single append to the DOM via the fragment instead of multiple appends. This gives better performance, especially if you have a large set of data.
使用 a 的好处documentFragment
是您可以通过片段对 DOM 执行单个附加,而不是多个附加。这提供了更好的性能,尤其是当您有大量数据时。
回答by rlemon
Better late than never... I recently made a lib to do just this!
迟到总比不到好......我最近做了一个库来做到这一点!
FragBuilderis the library.. usage is pretty simple: for the example you have posted you would need to change around the JSON a bit to make it a bit more semantic...
FragBuilder是库.. 用法非常简单:对于您发布的示例,您需要稍微更改 JSON 以使其更具语义...
var frag = [{"items": [
{
"title": "sample 1",
"author": "author 1"
},
{
"title": "sample 2",
"author": "author 2"
}
]}];
would become
会成为
var frag = [ { "childNodes" : [ { "childNodes" : [ { "textContent" : "sample 1" } ],
"tagName" : "H5"
},
{ "childNodes" : [ { "textContent" : "By: author 1" } ],
"tagName" : "P"
},
{ "childNodes" : [ { "textContent" : "sample 2" } ],
"tagName" : "H5"
},
{ "childNodes" : [ { "textContent" : "By: author 2" } ],
"tagName" : "P"
}
],
"className" : "news-story",
"tagName" : "DIV"
} ];
then you would generate a DocumentFragment by calling FragBuilder(frag)
那么你将通过调用生成一个 DocumentFragment FragBuilder(frag)
There is also a reverse function if you find it easier to template using HTML then convert to JSON https://gist.github.com/2313580(note, whitespace between tags is not handled and will cause failures)
如果您发现使用 HTML 模板更容易,然后转换为 JSON https://gist.github.com/2313580,还有一个反向功能(注意,标签之间的空格未被处理,会导致失败)
回答by Adam
I've found that the most reliable way to create DOM elements is using the element.innerHTML
property. Basically you'd have a DIV or SPAN at the place at the place on the page where you want to render the new HTML. Then you'd grab that span in javascripting using document.getElementById("DIV-ID")
and then set the innerHTML
property of the DIV to the new HTML that you would generate from the JSON object. There are a bunch of other JavaScript functions to create elements, but I've found that they're not always reliable and don't always have the best cross-browser support.
我发现创建 DOM 元素最可靠的方法是使用element.innerHTML
属性。基本上,您在页面上要呈现新 HTML 的位置有一个 DIV 或 SPAN。然后,您将使用 javascripting 获取该跨度,document.getElementById("DIV-ID")
然后将innerHTML
DIV的属性设置为您将从 JSON 对象生成的新 HTML。有许多其他 JavaScript 函数可以创建元素,但我发现它们并不总是可靠的,并且并不总是具有最好的跨浏览器支持。
回答by MilkyWayJoe
Sample with no jQuery:
没有 jQuery 的示例:
<html>
<head>
<title>test</title>
</head>
<body>
<div class="news-story">
<h5>sample 1</h5>
<p>By: author 1</p>
<h5>sample 2</h5>
<p>By: author 2</p>
</div>
<script type="text/javascript">
var json = {
"items": [
{
"title": "sample x",
"author": "author x"
},
{
"title": "sample y",
"author": "author y"
}
]
};
var bindDataToHTML = function(data, element) {
var h5 = null;
var p = null;
h5 = element.getElementsByTagName("h5");
p = element.getElementsByTagName("p");
h5[0].innerText = data.items[0].title;
h5[1].innerText = data.items[1].title;
p[0].innerText = data.items[0].author;
p[1].innerText = data.items[1].author;
};
document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\b'+cl+'\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) { retnode.push(elem[i]); }
}
return retnode;
};
// For sample purpose, let's imagine this method is a callback
// for a request that provides you with your json data
var doRequest = function() {
var data = json;
var element = null;
var x = document.getElementsByClassName("news-story");
if((null != x) && (0 < x.length)) {
element = x[0];
}
bindDataToHTML(data, element);
};
(function() {
doRequest();
})();
</script>
</body>
</html>
回答by transformer
Try JsRender and JsViews or moustache/ember
尝试 JsRender 和 JsViews 或小胡子/余烬
回答by Jalal Daultana
$(document).ready(function () {
loadfunctionAjax();
});
var loadfunctionAjax = function () {
$.ajax({
type: 'GET',
url: '/Site/SocialLink',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var HTML = '';
for (var i = 0; i < data.length; i++) {
item = data[i];
HTML += '<li><a class="" target="_blank" href="' + item.FALink + '"><i class="fa ' + item.FAIcon + '"></i>' + item.Name + '</a ></li > ';
}
$('#footerSocialNav').append(HTML);
}
});
}