javascript - 根据最终用户的时间调用样式表的 js 代码优化
问题描述
以下代码有效。这很简单,但我确信在不使用 jquery 的情况下会有更好和/或更优化的方式来编写它,但我不知道有任何其他方式可以做到这一点并让它像现在一样工作。
<script>
function getStylesheet() {
var currentTime = new Date().getHours();
if (5 <= currentTime&¤tTime < 11) {
document.write("<link rel='stylesheet' href='{T_THEME_PATH}/morning.css'>");
}
if (11 <= currentTime&¤tTime < 16) {
document.write("<link rel='stylesheet' href='{T_THEME_PATH}/day.css'>");
}
if (16 <= currentTime&¤tTime < 22) {
document.write("<link rel='stylesheet' href='{T_THEME_PATH}/evening.css'>");
}
if (22 <= currentTime&¤tTime <= 24 || 0 <= currentTime&¤tTime < 5) {
document.write("<link rel='stylesheet' href='{T_THEME_PATH}/night.css'>");
}
}
getStylesheet();
编辑:我只需要知道是否有更好的方法来编写我发布的 js。更好的是我有什么缺陷或不正确的编码
解决方案
尽管主要问题是在插入元素时使用document.write
它通常被认为是不好的做法,但您的方法对于您正在做的事情大多是好的。如果你想稍微清理一下,你可以做这样的事情,它专注于断点而不是值的范围:
function getStylesheet() {
const currentTime = new Date().getHours();
const breaks = [5, 11, 16, 22, 24];
const extensions = ['night', 'morning', 'afternoon', 'evening', 'night'];
const match = breaks.findIndex(num => currentTime < num);
const head = document.getElementsByTagName('head')[0];
const sheetLink = document.createElement('link');
sheetLink.rel = 'stylesheet';
sheetLink.href = `T_THEME_PATH/${extensions[match]}.css`;
head.appendChild(sheetLink);
}
getStylesheet();
这种方法假定时间格式始终为 0-24,并且要求两个数组完全相关,因此它不是那么灵活,但您可能喜欢使用它。它还使用模板文字来构造href
一次,而不是多次写出。
最后一点 - 您的代码中没有 jQuery,它都是香草 javascript。
推荐阅读
- python - 想要在单击按钮时将条目框中的文本添加到 .txt 文件中,但我收到一条错误消息,提示“未定义文本”
- regex - 使用正则表达式从 Perl 中的字符串中删除多余的管道和文本
- python - 为 Python 3.8、Windows 安装 PySide2
- r - 将 data.frame 转换为具有数字和字符数据特定排序的行?
- angularjs - AngularJs ng-repeat 在范围更改后不排序时间列表
- mysql - Docker Compose:将 WordPress 容器连接到 MySQL 容器?
- firebase - how to handle firebase auth exceptions in flutter?
- reactjs - use create-react-app and don't have any folder
- quantum-computing - How to pass one Q# operation to another Q# operation from C# or F#
- php - 管理雇主的 SQL 请求或 php 解决方案