(放轻松,我只是在学习 HTML/JavaScript)我想要一个仅显示人名的列表,但是当单击列表项时,我想知道其余的人数据。例如,给定下面的 JSON 数据,如果我单击“Sally”,我想访问该 Sally 的年龄和性别(可能有多个 Sally)。[ { "name": "Charlie", "age": "9", "gender":"M" }, { "name": "Sally", "age": "43", "gender": "F" }, { "name": "Will", "age": "20", "gender": "M" }, { "name": "Sally", "age": "18", "gender": "F" }]有没有办法在不显示的情况下向列表项添加额外信息?就像是<li class="list-item" age="18" gender="F">Sally</li>
2 回答
波斯汪
TA贡献1811条经验 获得超4个赞
单击该元素时,您应该获取该特定节点的数据,而不是使用数组过滤器将其与您的数据集匹配。您可以在此处查看有关数组过滤器的更多信息:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
document.querySelectorAll('li').forEach(item => {
item.addEventListener('click', event => {
// handle click
console.log(item)
// data would be the array of objects, you provided
let result = data.filter(person => person.name == item.innerText);
// this would return two elements from your array with "Sally"
console.log(result);
})
})
添加回答
举报
0/150
提交
取消