无法使用javascript中的select从json获取数据

时间:2017-10-03 17:31:03

标签: javascript json

我是Json和javascript的新手。我想要的是带选项的select标签,因此通过选择选项 - 将从JSON获取特定对象并将显示,我使用了嵌套JSON。

data.json:

var data = {

        "abc":{
            "color":["rgb(4,45,97)","rgb(255,122,0)"],
            "font":"Interface Thin",
            "logo":"<img src='logo.png' width='200' height='150'>"
        }


    }

的index.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="data.json"></script>
</head>

<body>
<!--document.getElementById('color').innerHTML += '<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.AllenandHanburys[j]+';height:100px"></div>'-->

<p id="demo"></p>
<p id="color"></p>
<p id="logo"></p>

<select id="brand" onChange="run()"> 
    <option>Select Option</option>
    <option value="abc">abc</option>
</select>
</body>

<script>
var i;
function run() {
var brand_name=document.getElementById('brand').value;//
for(x in data)
{
    if(x==brand_name)
    {
        for(j in data.brand_name)
            {
                document.getElementById('demo').innerHTML +=j+":"+data.abc[j]+"<br>";
                if(j=='color')
                    {
                            for(i=0;i<data.abc.color.length;i++)
                            {
                                document.getElementById('color').innerHTML +='<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.abc.color[i]+';height:100px"></div>'+"<br>";
                            }


                    }



            }
    }
}
}
</script>

</html>

1 个答案:

答案 0 :(得分:1)

这条线错了,

for(j in data.brand_name) //because `brand_name` property is not exist in the object

将其更改为

for(j in data[brand_name]) //data[brand_name] will parsed as data['abc'] which is same as data.abc

以下是演示

var data = {

        "abc":{
            "color":["rgb(4,45,97)","rgb(255,122,0)"],
            "font":"Interface Thin",
            "logo":"<img src='logo.png' width='200' height='150'>"
        }


    }



var i;
function run() {
var brand_name=document.getElementById('brand').value;//
for(x in data)
{
    if(x==brand_name)
    {
        for(j in data[brand_name])
            {
                document.getElementById('demo').innerHTML +=j+":"+data.abc[j]+"<br>";
                if(j=='color')
                    {
                            for(i=0;i<data.abc.color.length;i++)
                            {
                                document.getElementById('color').innerHTML +='<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.abc.color[i]+';height:100px"></div>'+"<br>";
                            }


                    }



            }
    }
}
}
<p id="demo"></p>
<p id="color"></p>
<p id="logo"></p>

<select id="brand" onChange="run()"> 
    <option>Select Option</option>
    <option value="abc">abc</option>
</select>