【发布时间】:2021-10-25 00:08:34
【问题描述】:
function ageInDays() {
var birthYear = prompt('What year were you born');
//Subtracts your birthyear from the current year, and multiplys by 365 (365 days in a year)
var ageInDayss = (2021 - birthYear) * 365 ;
//Creates a h1 element
var h1 = document.createElement('h1');
//Creates the text 'you are (age in days) days old'
var textAnswer = document.createTextNode('You are ' + ageInDayss + ' days old ');
//The setAttribute() method adds the specified attribute to an element, and gives it the specified value
h1.setAttribute('id', 'ageInDayss');
//The appendChild() method appends (adds) a node as the last child of a node
h1.appendChild(textAnswer);
//The Document method getElementById() returns an Element object representing the element whose id property matches the specified string
document.getElementById('flex-box-result').appendChild(h1);
}
function reset() {
document.getElementsById('ageInDays').remove();
}
<body>
<div class="container-1">
<h2>Challenge 1: Your Age in Days </h2>
<div class="flex-box-container-1">
<div>
<button class="btn btn-primary" onclick="ageInDays()">Click Me</button>
</div>
<div>
<button class="btn btn-danger" onclick="reset()">Reset</button>
</div>
</div>
<div class="flex-box-container-1">
<div id="flex-box-result"></div>
</div>
</div>
<script src="static/script.js"></script>
</body>
</html>
我正在学习如何使用 HTML、CSS 和 Javascript 以天为单位计算您的年龄的教程。我设法让“点击我”按钮工作并以天为单位计算我的年龄。但是,当谈到红色的“重置”按钮时,它就不起作用了。它只是不起作用,请帮助!
【问题讨论】:
-
请向我们提供mcve。不要只粘贴 YouTube 网址,因为它有几个缺点。也就是说,你让那些试图帮助你的人花费比需要更多的空闲时间。也可以将其视为您只是想获得视频的观看次数和喜欢等。获取无法按预期工作的代码部分并将其放入您的问题中。解释它应该做什么以及您在浏览器控制台中遇到的任何错误。
-
欢迎来到 Stack Overflow!没有人能告诉你我们看不到的代码有什么问题。要了解有关此社区的更多信息以及我们如何为您提供帮助,请从 tour 开始并阅读 How to Ask 及其链接资源。
-
这是因为
reset是input的内置功能,用于reset任何值input但它不能删除您在input中输入的任何值使用一个function。因此,当单击reset并删除该功能时,您必须添加一个额外的function。我也面临这个问题,并通过尝试不同的困难方法得到它 -
您能否将代码发送给我,因为我是 js 的初学者。这是代码 function reset() { document.getElementsById('ageInDays').remove(); }
-
那是因为
document.getElementsByIdis not a function。另外,(2021 - birthYear) * 365不是您的年龄。
标签: javascript html css dom