javascript - 如何使用 javascript 将 json 对象附加到 html 正文?(没有 jQuery)
问题描述
我的网站写在“content.json”文件中,所以我的 html.index 有一个空的正文。目前我可以 console.log 'script.js' 中的所有元素,我可以在控制台中看到我在 'content.json' 中声明的所有 div。我的问题是如何将所有这些元素附加到 html 正文中,这样我才能真正看到我用 json 编写的所有 div?
我使用递归从 .json 和 console.log() 中获取所有这些元素。这是我的 json 文件(以防万一)。https://textuploader.com/15820
function loadJSON(callback) {
var req = new XMLHttpRequest();
req.overrideMimeType('application/json');
req.open('GET', 'https://api.myjson.com/bins/ohp3s', true); // myjson.com url
req.onreadystatechange =
function() {
if (req.readyState == 4 && req.status == "200") {
callback(req.responseText);
}
};
req.send(null);
}
function get(data){
el = document.createElement(data.type);
if(typeof el.id === 'string'){
el.id = data.id;
}
if(typeof el.className === 'string'){
el.className = data.className;
}
if(typeof el.src === 'string'){
el.src = data.src;
}
if(typeof el.href === 'string'){
el.href = data.href;
}
if(typeof el.innerHTML === 'string'){
el.innerHTML = data.innerHTML;
}
if(typeof el.alt === 'string'){
el.alt = data.alt;
}
return el;
}
function recurseJSON(data){
for(let i of data.content) {
console.log(get(i));
if (typeof i.content === 'object'){
recurseJSON(i);
}
}
}
function initJSON() {
loadJSON(function(res) {
recurseJSON(JSON.parse(res));
});
}
initJSON();
解决方案
appendChild
使用方法附加元素。
document.body.appendChild(get(i));
推荐阅读
- kotlin - Kotlin - 在 foreach 中使其可变
- c++ - 使用 N-API 时如何避免分段错误?
- excel - 在 VBA for Excel 中创建类型搜索敏感组合框
- angular - 检测从剪贴板中的 gmail 拆分的行(角度)
- java - 导入 javax.xml.ws.BindingProvider;失败
- c++ - 创建具有不同返回类型的 lambda?
- python - 如果原始 dtype 未知,如何在从字节加载时找到 numpy recarray 的 dtype
- node.js - 是否有解决方法来处理 Cloud Functions 中的错误“错误:4 DEADLINE_EXCEEDED:超出期限”
- php - 如何从数组的字符串中获取第一个标题
- python - 如何使用 repr() 的多个实例