首页 > 解决方案 > 为什么在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>

标签: javascripthtmlfunction

解决方案


你需要调用函数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>


推荐阅读