首页 > 解决方案 > 输入年龄后有没有办法删除结果?

问题描述

一直试图找出一种方法来删除我按下Reset按钮时我的弹性框结果的结果。尝试了所有我能想到的并且对 JavaScript 非常陌生的东西,因此非常感谢任何帮助和解释。我不知道我的 JavaScript 文件是否有问题或没有正确调用它。

let button = document.getElementById('action');
button.addEventListener('click', function() {
  let birthYear = prompt("what year were you born...Good friend?");
  let ageInDays = (2020 - birthYear) * 365;
  let h1 = document.createElement('h1');
  let textAnswer = document.createTextNode('You are ' + ageInDays + 'days old');
  h1.setAttribute('id', 'ageInDays');
  h1.appendChild(textAnswer);
  document.getElementById('flex-box-result').appendChild(h1);
  console.log(ageInDays);
});

const button2 = document.getElementById('Reset');
button.addEventListener('click', function() {
  document.getElementById('flex-box-result').remove

})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"></link>

<div class="container-1">
  <h2>Challenge 1: How Many Days You Have Lived</h2>
  <div class="flex-box-container-1">
    <div>
      <button class="btn btn-primary" id="action">Click Here></button>
    </div>
    <div>
      <button class="btn btn-danger" id="Reset">Reset</button>
    </div>
    <div class="flex-box-container-1">
      <div id="flex-box-result"></div>
    </div>
  </div>
</div>

标签: javascripthtmlcss

解决方案


如果你想要 IE 支持,你可以使用removeChild

let button = document.getElementById('action');
button.addEventListener('click', function() {
  let birthYear = prompt("what year were you born...Good friend?");
  let ageInDays = (2020 - birthYear) * 365;
  let h1 = document.createElement('h1');
  let textAnswer = document.createTextNode('You are ' + ageInDays + 'days old');
  h1.setAttribute('id', 'ageInDays');
  h1.appendChild(textAnswer);
  document.getElementById('flex-box-result').appendChild(h1);
  console.log(ageInDays);
});

const button2 = document.getElementById('Reset');
button2.addEventListener('click', function() {
  const result = document.getElementById('flex-box-result');
  const child = result.childNodes[0]
  if (child) result.removeChild(child);
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"></link>

<div class="container-1">
  <h2>Challenge 1: How Many Days You Have Lived</h2>
  <div class="flex-box-container-1">
    <div>
      <button class="btn btn-primary" id="action">Click Here></button>
    </div>
    <div>
      <button class="btn btn-danger" id="Reset">Reset</button>
    </div>
    <div class="flex-box-container-1">
      <div id="flex-box-result"></div>
    </div>
  </div>
</div>


推荐阅读