首页 > 解决方案 > 如何使用 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();

标签: javascripthtmljson

解决方案


appendChild使用方法附加元素。

document.body.appendChild(get(i));

推荐阅读