removeChild来自另一个模块

时间:2017-11-28 22:53:28

标签: javascript dom removechild dom-events

我试图在设置的时间到期时删除childNode。当倒计时达到0.我想删除提交答案的按钮,停止播放器提交答案。该按钮是在除计时器之外的另一个模块中创建的,这似乎是一个问题。有没有办法删除childNode(按钮)或有另一种方法以某种方式杀死按钮的功能? 来自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)

Module2的代码

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()
}

1 个答案:

答案 0 :(得分:1)

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

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)
}