javascript - 为什么在winOrNot函数中输入参数(false)时代码不会隐藏html div?
问题描述
当使用 (false) 参数调用函数时,为什么这段代码不隐藏 div 中的“恭喜”消息?
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="winner">Congratulations!</div>
<script>
var winner = function winOrNot(winner) {
//if the variable winner has the value of true, show the div with id "winner"
if(winner) {
document.getElementById('winner');
}
//otherwise, hide the div if the value of winner is false
else {
document.getElementById('winner').style.display = 'none';
}
winOrNot(false);
}
</script>
</body>
</html>
更新:感谢您的建议。我已经用你的想法更新了我的代码,但在保存编辑并运行代码后我仍然得到相同的结果。这是修订:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#winner {
display:block;
}
</style>
</head>
<body>
<div id="winner">Congratulations!</div>
<script>
var winner = function winner(winner) {
//if the variable winner has the value of true, show the div with id "winner"
if(winner) {
document.getElementById('winner');
}
//otherwise, hide the div if the value of winner is false
if(winner===false) {
document.getElementById('winner').style.display = 'none';
}
}
winner(false);
</script>
</body>
</html>
解决方案
你需要调用函数winOrNot
。您的函数调用( winOrNot(false)
) 在winOrNot
.
此外,为了将状态从 更改回来display: none
,我们需要设置display: block
我们隐藏的元素。
winOrNot(false);
setTimeout(() => winOrNot(true), 2000);
function winOrNot(winner) {
//if the variable winner has the value of true, show the div with id "winner"
if (winner) {
document.getElementById('winner').style.display = 'block';
}
//otherwise, hide the div if the value of winner is false
else {
document.getElementById('winner').style.display = 'none';
}
}
<h5>should change after 5 seconds</h5>
<div id="winner">Congratulations!</div>
推荐阅读
- keycloak - 带有keycloak的nginix:登录时出错:请求redirect_uri_path但没有找到会话状态
- javascript - 从多个日期输入计算总天数
- angular - 任何用于将目录创建为索引的 Angular 模块或库
- javascript - javascript 上的循环实现
- autocomplete - Sublime Anaconda 包滥用 auto_complete(删除特定触发器)
- typescript - 将 Typescript 装饰器限制为 void 或 Promise
功能 - architecture - 如何计算特定 QPS(每秒查询数)需要多少台服务器
- javascript - 打字稿一衬线字符串声明
- unity3d - 镜像多人播放器颜色更新未在其他客户端上显示
- android - 无法从 Android 11 设备中的服务启动活动