使用 JavaScript 三元运算符根据当前时间显示办公室现在是关门还是开门

javascriptweb developmentobject oriented programming更新于 2025/11/14 0:12:17

假设我们将当前日期和时间与营业时间进行匹配。我们需要根据当前时间显示办公室现在是关门还是开门。

从当前日期获取小时数,可以使用三元运算符来显示关门和开门。以下是代码 −

示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<p class="closeOrOpened"></p>
<script>
   const gettingHours = new Date().getHours()
   const actualHours = (gettingHours >= 10 && gettingHours < 18) ? 'Open' : 'Closed';
   document.querySelector('.closeOrOpened').innerHTML = actualHours;
</script>
</body>
</html>

要运行上述程序,请将文件名保存为"anyName.html(index.html)",然后右键单击该文件。在 VS Code 编辑器中选择选项"使用 Live Server 打开"。

输出

将产生以下输出 −

Open

现在我的当前时间小于 10,因此,我给出了条件,当小时小于 10 时,将获得关闭的输出。


相关文章


有用资源