document.write和json数组

时间:2018-09-29 14:19:35

标签: javascript jquery html

开始我的代码:

    <!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> 
    <title>New Help</title>
</head>
<body>
    <table>
    <tr>
        <th>ID</th>
        <th>Login</th>
        <th>Password</th>
        <th>Site</th>
    </tr>
    <tr id="tabela">
    <script type="text/javascript">
        getData()
    </script>
</tr>
    </table>
</body>
</html

CSS:

body
{
    background: #4800FF;
    margin: auto;
    font-family: 'Roboto', sans-serif;
    color: white;
}

table
{
    text-align: left;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
th{
    min-width: 100px;
    background: #3001B8;
}

JS:

function getData() {
    var userData;
    $.getJSON("info.json", function(info) {
        userData = info;
        len = Object.keys(info).length;
        console.log(len);

        var i;
        for (var i = 0; i < len; i++) {
            document.write("<tr><td style='background-color: #350080'>" + userData[i].id + "</td><td style='background-color: #350080'>" + userData[i].login + "</td><td style='background-color: #350080'>"+ userData[i].password +"</td><td style='background-color: #350080'>"+ userData[i].site +"</td></tr>")
        }
    });
}

和我的JSON:

 [
        {
            "id":"1",
            "login":"loginTest",
            "password":"testpass",
            "site":"testSite"
        },
        {
            "id":"1",
            "login":"loginTest",
            "password":"testpass",
            "site":"testSite"
        }
    ]

问题是document.write在表中没有给我输出,而是在单独的页面上显示,当代替document.write时,我会给console.log,在控制台中我得到与表和html匹配的输出代码,在此先感谢您的帮助 screen

0 个答案:

没有答案