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

时间:2017-02-15 13:01:39

标签: javascript html json dropdownbox

我一直在尝试使用虚拟JSON数据填充div表,但我似乎无法做到这一点。我想要做的是根据下拉框中的选择显示某些数据。此外,我还需要在选择项目时使用新的下拉框创建新行。你能给我一些建议,告诉我最好的方法吗?我能够在Angular中创建接近我需要的东西,但我需要纯JavaScript。提前致谢!

structure of my div tables

2 个答案:

答案 0 :(得分:0)

假设在数据中你有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-row的相应下拉元素中的table和num,如下图所示。enter image description here

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);
    }
}

答案 1 :(得分:0)

这可以通过以下代码实现:您还可以在此处查看示例: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>