繁体   English   中英

结合两个不同的 JavaScript 函数来获取 JSON 兄弟数据

[英]Combining two different JavaScript functions to get JSON sibling data

我有两个功能。 一个-在“点击”上获得 id 值。 第二 - 从一个 id 获取兄弟数据。

我想结合这两个函数,所以当我点击一个 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"));
  });
}

您可以将逻辑直接放入匿名函数中并使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM