我有一个包含一些对象的JSON文件。 想要根据下拉选择填充对象。 下拉列表包含所有" Level"值,我需要只显示包含" Level"值等于用户选择。 请参阅以下链接
https://fiddle.jshell.net/agbpr021/
for (var i = 0; i < allData.length; i++) {
var x = document.getElementById("level").value;
if(x = allData.level)
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = allData[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
答案 0 :(得分:0)
这应该可以为您提供所需的结果。可能是一种更有效的方法,例如我为表格创建html,但它应该为您提供所需的输出。
function CreateTableFromJSON()
{
// only included this so snippet would work
allData = [
{ "Level": "a", "Country": "Unknown", "Currency": "USD" },
{ "Level": "a", "Country": "All", "Currency": "BRL" },
{ "Level": "b", "Country": "All", "Currency": "EUR" },
{ "Level": "c", "Country": "All", "Currency": "EUR" },
{ "Level": "d", "Country": "None", "Currency": "EUR" }
]
var x = document.getElementById("Levels").value;
var index = -1;
for (var i = 0; i < allData.length; i++) {
if (allData[i].Level == x)
index= i;
}
var html = "";
if (index != -1) {
// probably a better way to do this portion
html = "<table><thead><tr><th>Level</th><th>Country</th><th>Currency</th></tr></thead><tbody><tr>";
html += "<td>" + allData[index].Level + "</td>";
html += "<td>" + allData[index].Country + "</td>";
html += "<td>" + allData[index].Currency + "</td>";
html += "</tr></tbody></table>";
} else {
html = "Please make a selection";
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = html;
}
&#13;
<p>levels</p>
<select id="Levels">
<option value="Null" id="m">Choose level</option>
<option value="a" id="A">a</option>
<option value="b" id="B">b</option>
<option value="c" id="C">c</option>
<option value="d" id="D">d</option>
</select>
<br /><br />
<!--Button-->
<input type="button" onclick="CreateTableFromJSON()" value="Go" />
<div id="showData"></div>
<br>
&#13;
编辑:我想提一下真正聪明的人把工具放在一起来处理这个问题。 React,Vue和Angular是一些为这类东西提供工具的例子。
编辑:在allData中添加了对错误索引的检查