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

JavaScript函数结果无法以文本形式打印的问题排查

问题分析与修复方案

核心问题点

  • 变量名重复覆盖:多次用workouts命名不同类型的变量(数组、DOM元素、随机数),导致变量引用完全混乱。
  • 未定义变量:点击事件里直接使用workouts[num],但num从未声明和赋值。
  • 按钮元素未获取:代码直接调用button变量,但没有先通过DOM方法获取对应的按钮元素。
  • querySelectorAll参数错误:该方法仅接受一个包含多选择器的字符串参数,你传入多个独立参数,无法正确选中目标元素。
  • 显示/打印逻辑错误:print(workouts)里的workouts此时已被覆盖为随机数,且print()是触发浏览器打印页面,不是把内容显示到页面上。

修正后的代码

// 修正querySelectorAll参数,多选择器放在一个字符串里用逗号分隔
const hiddenElements = document.querySelectorAll(".hidden, .demo, .hold, .button, hold");
hiddenElements.forEach((el) => observer.observe(el));

// 数组变量改名,避免和DOM元素变量冲突
const workoutList = [
  "10 push ups",
  "5 pull ups",
  "15 box squats",
  "10 jump squats",
  "8 single leg squats",
  "20 mountain climbers",
  "1 minute plank",
  "20 resistance band pull-aparts",
  "30 second bar hang",
  "15 second hangboard",
  "5 diamond push ups",
  "5 military/wide push ups",
  "15 lunges",
  "1 minute skip rope",
  "30 second wall sit",
];

// 获取显示内容的DOM元素和按钮元素(按钮id按需修改)
const displayElement = document.getElementById("workouts");
const button = document.getElementById("button");

button.addEventListener("click", function () {
  // 生成数组范围内的随机索引
  const randomIndex = Math.floor(Math.random() * workoutList.length);
  // 把随机选中的内容显示到页面上
  displayElement.innerText = workoutList[randomIndex];
  // 如果需要打印页面,取消注释下面一行;仅显示内容则无需此代码
  // window.print();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:20:58