从另一个模块中移除子对象

removeChild from another Module

我正试图在设置的时间到期时删除一个 childNode。当倒计时达到0时。我想删除提交答案的按钮,停止玩家提交答案。该按钮是在计时器之外的另一个模块中创建的,这似乎是一个问题。有没有办法删除 childNode(button) 或者是否有另一种方法以某种方式终止按钮的功能? 来自 Module1

的代码
let answerDiv = document.querySelector('#answer')
let input = document.createElement('input')
input.type = 'text'
answerDiv.appendChild(input)


let button = document.createElement('button')
button.type = 'button'
button.setAttribute('id', 'button')
button.innerText = 'Answer'
answerDiv.appendChild(button)

来自模块 2 的代码

function timer () {
  let seconds = 21

  function countDown () {
    let counter = document.querySelector('#timer')
    seconds--
    counter.innerText = seconds.toString()
    if (seconds > 0) {
      setTimeout(countDown, 1000)
    }

    if (seconds === 0) {
      counter.innerText = 'Too slow!'
      let remove = document.querySelector('#button')
      remove.removeChild(remove)
    }
  }
  countDown()
}

您想要做的是从 #answer 容器中移除 #button,而不是:

if (seconds === 0) {
  counter.innerText = 'Too slow!'
  let remove = document.querySelector('#button')
  remove.removeChild(remove) // HERE YOU TRY TO REMOVE A NODE EXISTING INSIDE THE SAME NODE, THAT DOESN'T MAKE SENSE
}

这样做:

if (seconds === 0) {
  counter.innerText = 'Too slow!'
  let answerDiv = document.querySelector('#answer')
  let remove = document.querySelector('#button')
  answerDiv.removeChild(remove)
}