You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将星期几动态插入JS随机生成通知语句的指定位置

实现方案

核心逻辑是在随机取出第一条句子后,将占位符«weekday»替换为当前星期几的加粗文本,同时调整渲染方式支持HTML标签渲染:


核心修改点

  • 提前获取当前星期几,定义为可全局调用的变量
  • 随机取出第一组句子后,做占位符替换,给星期几添加强样式
  • 第一组文本渲染时改用innerHTML,避免HTML标签被当成纯文本显示

完整可运行代码

HTML代码

<div style="cursor: pointer;" onClick="setAleatoryNtfctnLines(); setAleatoryFarewell();">
    <div><span id="AleatoryNotification"></span> <span id="AleatoryFarewell"></span></div>
    <!-- 不需要单独显示星期几可以删除下面这行 -->
    <div><span id="weekday"></span></div>
</div>

JavaScript代码

<script>
// 提前获取当前星期几
const d = new Date();
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const currentWeekday = days[d.getDay()];
// 不需要单独显示星期几可以删除下面这行
document.getElementById("weekday").innerHTML = currentWeekday;

// 第一组通知文本数组
const FirstTextLines = [
"2 «weekday» comments done, for your 2 lectures",
"2 «weekday» comments done, on both your lectures",
"2 «weekday» comments for both your lectures",
"2 «weekday» comments for each of your lectures",
"2 «weekday» comments for your two lectures",
"2 «weekday» comments on both your lectures",
"2 «weekday» comments on each of your lectures",
"Already done 2 «weekday» comments x 2",
"Done 2 «weekday» comments on both your lectures",
"Done 2 «weekday» comments on each of your lectures",
"Done 2 «weekday» comments x 2",
"I just posted 2 «weekday» comments x 2",
"Just posted 2 «weekday» comments x 2"
];

const getAleatoryLines = max => Math.floor(Math.random() * max); 

const getAleatoryNtfctnLines = () => {
  // 取随机原始句子
  const rawLine = FirstTextLines[getAleatoryLines(FirstTextLines.length)];
  // 替换占位符为加粗的当前星期几
  return rawLine.replace('«weekday»', `<strong>${currentWeekday}</strong>`);
};

const setAleatoryNtfctnLines = () => {
  // 改用innerHTML渲染HTML标签
  document.getElementById('AleatoryNotification').innerHTML = getAleatoryNtfctnLines();
};

// 第二组结束语数组
const SecondTextLines = [
"Bye bye!",
"Bye for now.",
"Catch you later.",
"Have a good one.",
"Have a nice day.",
"Peace out.",
"Soon with more.",
"Take care.",
"Talk to you later.",
"Until next time."
];

const getAleatoryFarewellLines = max => Math.floor(Math.random() * max);

const getAleatoryFarewell = () => `${SecondTextLines[getAleatoryFarewellLines(SecondTextLines.length)]}`;

const setAleatoryFarewell = () => {
  document.getElementById('AleatoryFarewell').innerText = getAleatoryFarewell();
};

// 初始化渲染内容
setAleatoryNtfctnLines();
setAleatoryFarewell();
</script>

内容的提问来源于stack exchange,提问作者rx65m

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 20:36:01