javascript - 根据选定的“选项”更改 innerHTML 结果
问题描述
当我从下拉菜单中选择一个选项时,我试图拥有它,它将使用 data.json 文件中的正确信息更新结果。现在它将从 data[0] 返回字符串化数据,但我希望它根据所选选项 id 返回。因此,如果用户选择“Sarah”,即选项 id="4",我希望它从第 4 个 JSON 对象中获取数据。
<select id="options" onchange="myfunction()">
<option ></option>
<option id="0">Tyson</option>
<option id="1">Jessica</option>
<option id="2">Joshua</option>
<option id="3">Jennifer</option>
<option id="4">Sarah</option>
</select>
<br><br>
<div id="myData"></div>
function myfunction() {
fetch('data.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var mainContainer = document.getElementById("myData");
var div = document.createElement("div");
div.innerHTML = JSON.stringify(data[0], null, 4);
mainContainer.appendChild(div);
}
}
[
{
"id" : 0,
"first_name": "Tyson",
"gender": "male",
"isAlive": true,
"married": true,
"has_children": false,
},
{
"id" : 1,
"first_name": "Jessica",
"gender": "female",
"isAlive": true,
"married": true,
"has_children": false,
},
{
"id" : 2,
"first_name": "Joshua",
"gender": "male",
"isAlive": true,
"married": true,
"has_children": true,
},
{
"id" : 3,
"first_name": "Jennifer",
"gender": "female",
"isAlive": true,
"married": true,
"has_children": true,
},
{
"id" : 4,
"first_name": "Sarah",
"gender": "female",
"isAlive": true,
"married": false,
"has_children": false,
}
解决方案
首先,appendData
搬出myfunction
。它不需要嵌套。
其次,您需要在 中捕获下拉列表的选定值myfunction
,然后data
根据该值过滤您的集合。像这样的东西,也许:
function myfunction() {
var selectedId = document.getElementById("options").value; // e.g. "4" (string)
fetch('data.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
// let's filter the data
var person = data.filter(function(p) { return p.id == selectedId; });
appendData(person);
})
.catch(function (err) {
console.log('error: ' + err);
});
}
最后,您必须稍微调整您的appendData
函数以不再尝试索引该data
对象,因为它不再是一个数组:
function appendData(data) {
var mainContainer = document.getElementById("myData");
var div = document.createElement("div");
div.innerHTML = JSON.stringify(data, null, 4);
mainContainer.appendChild(div);
}
最后一个建议是不要将事件放在您的 HTML 属性中。这是非常过时的。相反,学习如何使用addEventListener
.
推荐阅读
- android - kotlin 中的 Android 应用程序不断崩溃
- android - 如何为警告对话框文本添加颜色
- python - 在 Python 中使用类型提示会影响性能吗?
- android - 将自定义应用程序类添加到生产应用程序
- paypal - 我可以用信用卡创建账单协议吗(没有贝宝账户)
- wpf - 如何从后面的代码中访问我的 ColumnDefinition Width 属性
- html - 在移动视图中实现视差滚动调整大小?
- python - Anaconda:撤消 conda 创建
- c# - 如何重命名从 ASP .NET Core 2.1 中的 IdentityUser 继承的类的 AspNetUsers 表?
- android - CoordinatorLayout 中的 Viewpager 不滚动