[英]Combining two different JavaScript functions to get JSON sibling data
I have two function.我有两个功能。 One- that on 'Click' gets the id value.一个-在“点击”上获得 id 值。 second- gets the sibling data from an id.第二 - 从一个 id 获取兄弟数据。
I want to combine the two functions, so when i click a div, get that 'id' and display the sibling data from JSON我想结合这两个函数,所以当我点击一个 div 时,获取那个 'id' 并显示来自 JSON 的兄弟数据
//this returns sibling data from JSON with id=2
const result = characters.find(item => {
// if this returns `true` then the currently
// iterated item is the one found
return item.id === 2
});
console.log(result);
//this allows me to click the different divs to get their id
var divs = document.querySelectorAll(".characterBox");
for(var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', function (event) {
console.log(this.getAttribute("id"));
});
}
You can put the logic directly into the anonymous function and use this.getAttribute("id")
instead 2
您可以将逻辑直接放入匿名函数中并使用this.getAttribute("id")
代替2
var divs = document.querySelectorAll(".characterBox");
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', function(event) {
const result = characters.find(item => {
return item.id == this.getAttribute("id")
});
console.log(result);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.