首页 > 解决方案 > 尝试控制台登录 foreach 回调函数

问题描述

如何在 foreach 回调函数中使用 console.log。我正在创建一个 html 描述列表并遍历一个 javascript 对象列表以附加到 dl 并将按钮添加到 dd 中。我的目标是将问题显示为 dt,并使用 dd 按钮隐藏/显示答案。为了更好地理解和弄清楚我将如何做到这一点,我试图控制每个按钮的 id。谢谢你。是codepen的链接。

const questions = [
  {
    statement: "2+2?",
    answer: "2+2 = 4"
  },
  {
    statement: "In which year did Christopher Columbus discover America?",
    answer: "1492"
  },
  {
    statement:
      "What occurs twice in a lifetime, but once in every year, twice in a week but never in a day?",
    answer: "The E letter"
  }
];


const content = document.querySelector('#content');
const dl = document.createElement('dl');
for (const question of questions) {
  const dt = document.createElement('dt');
  const dd = document.createElement('dd');
  dt.innerText = question.statement;
  const btn = document.createElement('button');
  dd.innerHTML = "<button>Show answer</button>";
  dd.id = question.answer;
  dl.appendChild(dt);
  dl.appendChild(dd);
  console.log(dd);
  dl.appendChild(document.createElement('br'));
}
content.appendChild(dl);

const buttons = document.querySelectorAll('button');
buttons.forEach(function(b){
  console.log(b.getAttribute("id"));
});

标签: javascript

解决方案


您正在选择没有属性 id 的按钮元素。您必须选择 dd 元素才能访问它们的 ID。

您可以使用

document.querySelectorAll('dd');

而不是使用

document.querySelectorAll('button');

推荐阅读