javascript - 尝试控制台登录 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"));
});
解决方案
您正在选择没有属性 id 的按钮元素。您必须选择 dd 元素才能访问它们的 ID。
您可以使用
document.querySelectorAll('dd');
而不是使用
document.querySelectorAll('button');
推荐阅读
- swift - 使用 `self` 作为静态/类方法的默认参数
- javascript - 单独的 html 文件和 javascript 文件中的 javascript 事件处理程序
- bash - How many threads will be started with shell script wait
- css - Make two columns separately scrollable and the height of the remaining length of the viewport
- javascript - 如何阻止浏览器从 marquee3K 崩溃?
- r - 如何将带有 twitter 数据的 Json 文件转换为 R 中的数据框?
- c# - textbox automatically assigning default value wpf
- javascript - Align inner tags of Touchable component in React Native
- graphviz - How to set head and tail position in nodes graphviz
- r - Why am I getting "Warning NaNs Produced" with ifelse?