我想要实现的目标
我有一个静态选择html选项,这些选项不会更改,但会确定其他选择框输出的内容。
<select id="firstselectbox">
<option value="first">This is the first</option>
<option value="second">This is the second</option>
<option value="third">This is the third</option>
<option value="fourth">This is the fourth</option>
<option value="fifth">This is the fifth</option>
</select>
目前,我编写的代码不想输出以下内容:
选择1:选项first
选择2:检查jSon文件,找到第一个和所有节点(第二层)并列出它们。当用户选择时。
选择3:显示第三层
请注意*
是下面选择的选项 - 选择1是静态的,选择2和3是动态的。
Select 1 Select 2 Select 3
first* London Famous Famous
second Jersey London Famous
third North*
fourth South East
fifth South West
sixth
到目前为止我做了什么
var datajson = {"first":[{"jesery":[{"id":"jesery","name":"Jesery","jesery":[{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"dontknow":[{"id":"dontknow","name":"Dont Know"}]}],"second":[{"london":[{"id":"london","name":"London","london":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}]}],"third":[{"london":[{"id":"london","name":"London","london":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"north":[{"id":"north","name":"North","north":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}]}],"forth":[{"north":[{"id":"north","name":"North","north":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"dontknow":[{"id":"dontknow","name":"Dont Know"}]}],"fifth":[{"london":[{"id":"london","name":"London","london":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"southeast":[{"id":"southeast","name":"South East","southeast":[{"id":"distance","name":"Distance"}]}]}]}
$("#firstselectbox").on('change', function() {
$("select#firstselectbox").html('');
var locations = datajson[$(this).val()];
var locationString = '';
$.each(locations, function(i, item) {
console.log(locations[i]);
locationString += '<option id="'+ locations[i].id + '" value="' + locations[i].id + '">' + locations[i].name + '</option>';
});
$('#secondselectbox').html(locationString);
});
问题吗
以下代码locationString += '<option id="'+ locations[i].id + '" value="' + locations[i].id + '">' + locations[i].name + '</option>';
正在输出unidentified
。
但是console.log(locations[i]);
正在输出从静态选择框(第一个,第二个等)中选择的数组。然而,试图将其分开似乎失败了。
当前代码正在输出unidentified
。
答案 0 :(得分:0)
使用不引人注目的JavaScript,这样您就不必像以前那样搜索错误:
$('#secondselectbox').empty()
$.each(locations, function(i, item) {
$("<option/>",{id:locations[i].id, value:locations[i].id, text:locations[i].name})
.appendTo('#secondselectbox')
})
编辑:您的JSON结构也存在问题。你基本上有一个包含单个对象的数组,所以当你使用数组时,你所处的位置比你需要的位置低一个级别。