【发布时间】:2016-11-24 16:04:13
【问题描述】:
我想加载一个选择框,用户选择的值会自动出现在其中。
我正在从服务器接收带有用户信息的 Json 数据。
数据样本为:{"color":"red"}
在我的 html 代码中,我有这样的选择选项:
<select id="input_user" class="selectinput" disabled="true">
<option value="n/a"> n/a </option>
<option value="red"> red </option>
<option value="green"> green </option>
<option value="yellow"> yellow </option>
<option value="blue"> blue </option>
<option value="white"> white </option>
</select> //this will only show "n/a" as default
我尝试使用此代码将红色值设为默认值,但不起作用。
var user_color= data[2].color; // this was from the json data
document.getElementById('input_user').selectedIndex = user_color;
有什么帮助吗?
【问题讨论】:
-
data是一个数组吗?您是否解析了来自服务器的 JSON? -
检查demo