我使用以下教程创建了一个太空入侵者游戏:http://www.html5rocks.com/en/tutorials/canvas/notearsgame/
我现在需要在javascript中使用json填充选择状态列表。我试过以下设置;我创建了一个div,可以显示选择框。
<body>
<h1>Game</h1>
<div id="displaycontent"></div>
<script type='text/javascript'>
我现在有回调函数来填充列表。
function getStates()
{
var url = "states_json.php";
req = new XMLHttpRequest();
req.open("GET", url, true);
//req.setRequestHeader("Accept","application/json; charset=utf-8");
req.onreadystatechange = getStatesCallBack;
req.send(null);
}
function getStatesCallBack()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
var response = req.responseText.parseJSON();
var displaycontent = document.getElementById("displaycontent");
while (displaycontent.hasChildNodes())
{
displaycontent.removeChild(displaycontent.lastChild);
}
var stateSelect = document.createElement("select");
stateSelect.setAttribute("id", "stateslist");
//artistSelect.setAttribute("onChange", "getArtistInfo()");
displaycontent.appendChild(stateSelect);
var state = response.statesarray;
for (i = 0; i <state.length; i++)
{
var state_id = state[i].state_id;
var state_name = state[i].state_name;
if (stateSelect != null && stateSelect.options != null)
{
stateSelect.options[stateSelect.options.length] =
new Option(state_name, state_id, false, true);
}
}
stateSelect.options[0].selected = true;
displaycontent.appendChild(stateSelect);
var stateDetailDiv = document.createElement("div");
stateDetailDiv.setAttribute("id", "statedetails");
displaycontent.appendChild(stateDetailDiv);
//getArtistInfo();
}
}
}
本教程中的游戏代码遵循上述代码。游戏运行正常,但根本没有填充选择列表。我检查了json文件输出,它显示正确的信息,这不是问题。我已尝试在firebug中进行调试,但它没有显示任何错误。
答案 0 :(得分:0)
您的选择列表的HTML最终应如下所示:
<select name="stateslist">
<option value="value1">Label For value 1</option>
<option value="value2">Label For value 2</option>
<option value="value3">Label For value 3</option>
</select>
因此,您应该尝试更改for (i = 0; i <state.length; i++)
循环的内容,并为每次迭代执行类似的操作:
var option = document.createElement("option");
option.setAttribute('value', state_id);
option.textContent = state_name;
stateSelect.appendChild(option);