gpt4 book ai didi

javascript - 根据执行的 if 语句切换 DOM 元素

转载 作者:行者123 更新时间:2023-11-28 02:27:24 25 4
gpt4 key购买 nike

我正在开发一个 JavaScript 项目,它会根据不同的方式向您致以不同的问候在一天中的时间是实时的。

例如,如果小时数小于 12,它会说早上好。但是我遗漏了一件事,我不知道如何添加。

我想要一个按钮和可能不同的 div,具体取决于哪个if/if else 语句被执行。例如,如果是早上,我会尝试显示“煮咖啡”按钮,如果是下午,则显示“打开电视”等。

问题是我不知道如何执行它。

<!DOCTYPE html>
<html>
<head>
<title>Greeting | Test</title>
</head>
<body align="center">

<style>

</style>

<script>

var Name = prompt("Hello! What is your name?");

var d = new Date();
var hour = d.getHours();
var min = d.getMinutes();
var hourAd = hour - 12;


if(hour < 12){ //target if statement to toggle button
document.write("Good Morning , " + Name + "." +
"<br /> It is currently " +
hour + ":" + min + " Am" );
//button code
}

else if(hour > 12){
document.write("Good Afternoon , " + Name + "." +
"<br /> It is currently " +
hourAd + ":" + min + " Pm" );
}

else if(hour > 19){
document.write("Good Evening , " + Name + "." +
"<br /> It is currently " +
hourAd + ":" + min + " Pm " );
}
</script>

<!--execute when if statement is true-->
<button id="coffee">Brew Coffee</button>
<button id="tv">Turn on TV</button>
<button id="dinner">Let's make dinner</button>
</body>
</html>

最佳答案

首先,您需要使用 style="display:none"document.getElementById("your display id").style.display = "block"隐藏所有 div ; 您可以按如下方式概述工作示例:

var Name = prompt("Hello! What is your name?");

var d = new Date();
var hour = d.getHours();
var min = d.getMinutes();
var hourAd = hour - 12;


if(hour < 12){ //target if statement to toggle button
document.write("Good Morning , " + Name + "." +
"<br /> It is currently " +
hour + ":" + min + " Am" );
//button code
document.getElementById("coffee").style.display = "block";
}

else if(hour > 12){
document.write("Good Afternoon , " + Name + "." +
"<br /> It is currently " +
hourAd + ":" + min + " Pm" );
document.getElementById("tv").style.display = "block";
}

else if(hour > 19){
document.write("Good Evening , " + Name + "." +
"<br /> It is currently " +
hourAd + ":" + min + " Pm " );
document.getElementById("dinner").style.display = "block";
}
 <!DOCTYPE html>
<html>
<head>
<title>Greeting | Test</title>
</head>
<body align="center">

<style>

</style>


<!--execute when if statement is true-->
<button id="coffee" style="display:none">Brew Coffee</button>
<button id="tv" style="display:none">Turn on TV</button>
<button id="dinner" style="display:none">Let's make dinner</button>

关于javascript - 根据执行的 if 语句切换 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53082544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com