javascript - 输入年龄后有没有办法删除结果?
问题描述
一直试图找出一种方法来删除我按下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>
解决方案
如果你想要 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>
推荐阅读
- c# - 使用 selenium 和 c# 添加到集合时如何过滤元素
- c++ - 尝试旋转空文件时提升日志rotate_file引发错误?
- java - 如何使用 Java 8 流组合逻辑以根据列表大小条件添加到列表中
- delphi - 无法使用 Delphi TWebBrowser 加载站点
- excel - 工作表中的命名范围计数在具有命名范围时结果为零
- foreign-keys - 我的 CRUD 应用程序应该对数据执行验证还是应该是数据库操作?
- javascript - 如何在 Visual Studio 中导入 JavaScript 库?
- sql - 从作为输入 oracle 传递的日期中查找星期
- laravel - Laravel 嵌套:事件(带时间线)和子事件(带时间线)
- visual-studio-code - 用于预定义文本替换的 VSCode 快捷方式/扩展?