gpt4 book ai didi

javascript - 访问 JSON 对象详细信息

转载 作者:行者123 更新时间:2023-11-30 16:33:39 25 4
gpt4 key购买 nike

我有一个简单的表单,可以提交所选位置的地址详细信息。在提交之前,我想让用户预览将要发送的地址。地址存储在 JSON 对象中。我有以下代码:

HTML:

<html>
<form action="something.asp" >
<select id="selectAddress">
<option value="Cheonan2">Cheonan 2</option>
<option value="Cheonan3">Cheonan 3</option>
</select>
<input type="submit"/>
</form>
<input type="button" value="Display addresses" onClick="showAddress()"/><br>

<span id="addressField1"></span>
<span id="addressField2"></span>
<span id="addressField3"></span>
</html>

JS:

<script>
function showAddress()
{
var JSONAddress =
[
{ "id":"Cheonan2",
"Field1": "96, 3Gongdan1-ro",
"Field2": "Seobuk-gu, Cheonan-si",
"Field3": "Chungcheongnam-do, 31093, Korea"
},

{
"id":"Cheonan3",
"Field1": "80, 3Gongdan6-ro,",
"Field2": "Seobuk-gu, Cheonan-si,",
"Field3": "Chungcheongnam-do, 31085, Korea"
}

];


var e=document.getElementById("selectAddress");
var selectedAddress = e.options[e.selectedIndex].value;

for (var i;i<JSONAddress.length;i++){
if (JSONAddress[i].id===selectedAddress){
document.getElementById('addressField1').innerHTML=JSONAddress[i].Field1;
document.getElementById('addressField2').innerHTML=JSONAddress[i].Field2;
document.getElementById('addressField3').innerHTML=JSONAddress[i].Field3;

}

}

}
</script>

我可能错误地访问了 JSONAddress 中的对象,因为该函数没有显示任何内容...你能帮忙吗?

最佳答案

首先,您没有在循环中将 var i 初始化为 0

其次,(在您的 fiddle 中)您使用了 getElementById - 它应该是 document.getElementById

第三,(在你的 fiddle 中)有 json.JSONAddress - 它应该只是 JSONAddress

Working Fiddle .

关于javascript - 访问 JSON 对象详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32989706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com