如何使用 JSON 和 Javascript 填充 div 表格和下拉框?

How to populate div tables and dropdownboxes with JSON and Javascript?

我一直在尝试用虚拟 JSON 数据填充 div 表,但我似乎做不到。我想要做的是根据下拉框中的选择显示某些数据。 Also I need to create new row with a new dropdownbox when an item is selected.你能给我一些关于什么是最好的方法的建议吗?我能够在 Angular 中创建接近我需要的东西,但我需要纯粹的 JavaScript。提前致谢!

structure of my div tables

假设在数据中你有json对象

var data = [
{
  "line": "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
  "author": "Brian W. Kernighan",
  "num" : ["1","2","3"]
},
{
  "line": "Walking on water and developing software from a specification are easy if both are frozen.",
  "author": "Edward V Berard",
  "num" : ["5","0","15"]
},
{
  "line": "It always takes longer than you expect, even when you take into account Hofstadter's Law.",
  "author": "Hofstadter's Law",
  "num" : ["15","222","301"]
}];

并且您想将 json 对象中的所有作者填充到 table 并将 num 填充到 table-row 的相应下拉元素中。然后按照 populateHTML() 函数将对象填充到 table 并将 num 填充到 table-row 的相应下拉元素中,如下图所示。

function populateHTML(data) {    
    if (typeof(data) == 'object') {
        document.write('<table>');
        for (var i in data) {
            document.write('<tr><td>'+data[i].author+'</td><td><select>');
            for(var j in data[i].num){
                 document.write('<option>' +data[i].num[j]+ '</option>');  
            }
            document.write('</select></td></tr>'); 
        }
        document.write('</tr></table>');
    } else {
        document.write(' => ' + data);
    }
}

这可以通过以下代码实现:您也可以在此处查看示例:http://skillcram.com/JS_DivTable.htm

<script type="text/javascript" >

function populateTable() {    

    var tableData = {
        products : [
            {"id": 100,"name":"Laptop", "qty":1,"status": ["Delivered","Damaged","Missing"]},
            {"id": 200,"name":"Monitor", "qty":2,"status":["Refused","Partial"]}
        ]
    }

    var  tableBody = document.getElementsByClassName("divTableBody");


    for (i in tableData.products){

        tableBody[0].innerHTML += "<div class=\"divTableRow\">  "   +
        "<div class=\"divTableRowCell\">"+ tableData.products[i].id +" </div>  "  +
        "<div class=\"divTableRowCell\">"+ tableData.products[i].name +" </div> " +
        "<div class=\"divTableRowCell\">"+ tableData.products[i].qty +" </div> "+
        "<div class=\"divTableRowCell\">"+ getSelectHTMl(tableData.products[i].status) +

        " </div> "+
        "</div>";

    }


}

function getSelectHTMl(status) {

    selectHTMlStr = "<select> ";

    for (j in status){
        selectHTMlStr +=            
        "<option value=\""+ status[j]+ "\" id=\"itemStatus\" >"+status[j]+ " </option>" ;

    }

    selectHTMlStr += "</select>" ;
    return selectHTMlStr;
}
</script>