javascript - 如何通过 JS fetch() 突出显示单击的项目

标签 javascript

这会使用 fetch() 从 json 文件加载选项,当我单击其中一个选项时,它应该突出显示(红色),但所有其他选项都应该为黑色。

它仅适用于第一个选项,为什么单击其他项目时其他选项不会变为黑色?

https://jsfiddle.net/03gphxdt/

let div = document.querySelector('div')

fetch('https://opentdb.com/api.php?amount=5').then(response => {
  return response.json()
}).then(data => {
  div.innerHTML = `
        ${data.results[0].incorrect_answers.map(incorrect_answer => `<p class="answer">${incorrect_answer}</p>`).join("")}
    	`
  div.addEventListener('click', function(event) {
    if (event.target.classList.contains('answer')) {
      // all items to be black (remove selected/red class )
      this.querySelector('.answer').classList.remove('selected')
      // add the selected/red class to only the item clicked
      event.target.classList.add('selected')
    }
  })
})
.answer {
  color: black;
}

.selected {
  color: red;
}
<div></div>

最佳答案

你是说这个吗?

let div = document.querySelector('div');

div.addEventListener('click', function(event) { // clicking the div
  this.querySelectorAll('.answer').forEach(item => item.classList.remove('selected')); // remove all selected
  if (event.target.classList.contains('answer')) {
    // add on the clicked answer only
    event.target.classList.add('selected')
  }
})

fetch('https://opentdb.com/api.php?amount=5').then(response => {
  return response.json()
}).then(data => {
  div.innerHTML = `${data.results[0].incorrect_answers.map(incorrect_answer => `<p class="answer">${incorrect_answer}</p>`).join("")}`

})
.answer {
  color: black;
}

.selected {
  color: red;
}
<div></div>

关于javascript - 如何通过 JS fetch() 突出显示单击的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59291228/

相关文章:

javascript - 为什么 dropzone js 以编程方式不能正常工作?

javascript - Backbone/Underscore Filter 多维集合

javascript - DOM 节点清理在 d3 中如何工作?

javascript - wit.ai 和 Node.js 入门

Javascript:意外的标记 else

php - javascript 中的变量,自动填充表单

javascript - 从 ios 应用程序调用 javascript 函数

javascript - 绝对 div 在 Google map 上抖动或消失

javascript - 单选按钮与列表的多个问题

javascript - 异步调用导致信息在加载之前显示