javascript - 如何从下拉选择中访问多维数组属性
问题描述
我正在为我的 JS 类分配作业,并试图根据用户从下拉菜单中的选择来找出如何从数组中访问特定属性。(我倾向于尝试比我们正在学习的东西更早的东西,并陷入这些束缚)
首先,我不知道如何实际调用这些数据。数据框?子集?地图?大批?多属性对象列表?(在为这篇文章创建标签后,我想知道这是否是一个多维数组)
如果描述得不好,我深表歉意。
到目前为止,我已经能够直接访问每个属性,但还没有弄清楚如何通过用户选择菜单进行访问。我在选项的 value 属性中添加了 id,但不知道如何在选择后使用它来访问其余属性。
这是我的脚本
const flavors = [
{
"flavor":"Tangy Taro Eggy",
"description":"",
"img_src":"images/tangy-taro-eggy.jpg",
"id": 1
},
{
"flavor":"Beetle Bark Raspberry",
"description":"",
"img_src":"images/beetle-bark-raspberry.jpg",
"id": 2
},
{
"flavor":"Cali CBD-licious Creme",
"description":"",
"img_src":"images/cali-cbd-licious-creme.jpg",
"id": 3
},
{
"flavor":"Durian Delight",
"description":"",
"img_src":"images/durian-delight.jpg",
"id": 4
},
{
"flavor":"Vanilla",
"description":"",
"img_src":"vanilla.jpg",
"id": 5
}
];
var select = document.getElementById("flavor_list"); //this is the id for <select> element in my HTML
flavors.forEach(function populate_list(item){
var option = document.createElement('option');
var img_src =flavors.img_src; //This one doesn't do anything becuase the value isn't read (which I don't know what that means)
//I tried defining this variable outside of the function as well but the alert still doesnt work
option.value = item.id; // I created unique values for each option but don't know how to use them to get more info
option.innerHTML = item.flavor;
select.appendChild(option)
})
select.onchange = function fetch_info() {
alert(this.img_src) // this is just a test to see if I got the info.
//Once I figure this out I will be able to complete there rest of the assignment
}
最好只使用 JS 而不要使用 Jquery 或类似的东西,因为我们还没有学到任何东西。
我很感激任何帮助
凯文
解决方案
也许将它的值作为一个 id 并循环遍历数组并找到确切的味道......
例子:
select.onchange = function (e) {
const id = e.target.value;
// find the set which has this id, as you have passed the option value your id
const flavor = flavors.filter(({ id: flavorId }) => +id === flavorId)[0];
console.log(flavor) // this is just a test to see if I got the info.
//Once I figure this out I will be able to complete there rest of the assignment
}
编辑:请确保,您的风味 id 是独一无二的。
推荐阅读
- lua - 防止lua窗口关闭
- c++ - 关于非并行和并行排序算法的问题?
- spring - 使用 spring cloud config 从 git-repo 获取 jks 文件
- c++ - 数组中的大量数字/C++
- javascript - 从 Puppeteer 中的 page.evaluate 获取元素?
- html - Flexbox 网格对齐图像中心
- ide - PhpStorm - 自动折叠所有方法体,不包括活动方法
- postgresql - 是否可以在 PostgreSQL 9.4 的 PL/pgSQL 函数中执行 IF 条件?
- opc - 报警和事件的 OPC 连接
- c++ - clang-tidy 在修复时插入多个“覆盖”说明符