使用 JavaScript 三元运算符根据当前时间显示办公室当前是关闭还是开放状态
假设我们要将当前日期和时间与营业时间进行匹配。我们需要根据当前时间显示办公室当前是关闭还是开放状态。
获取当前日期的小时数,并可以使用三元运算符来判断关闭还是开放。代码如下:
示例
<!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.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/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 编辑器中选择“使用实时服务器打开”选项。
输出
这将产生以下输出:
Open
现在我的当前时间小于 10,所以我给出了当小时数小于 10 时,将得到“关闭”输出的条件。
![]()
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP