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

JS实现点击生成按钮生成随机Newgrounds歌曲链接的问题排查

实现目标
  • 点击页面上的「Generate」按钮时自动生成全新的Newgrounds歌曲链接,无需手动输入ID,即可随机访问适用于《几何冲刺(Geometry Dash)》的平台歌曲
  • 不需要刷新页面,多次点击不会出现链接格式错误
原有代码问题说明
  1. 初版实现逻辑缺陷:每次点击都会读取当前链接的href值,在末尾直接拼接新随机数,多次点击后会出现ID重复叠加的无效链接,比如连续点3次就会生成类似https://www.newgrounds.com/audio/listen/123456789的错误地址,初版代码如下:
document.querySelectorAll("a").forEach(link =>
     link.setAttribute("href", link.getAttribute("href") + Math.floor(Math.random() * 111392.8) + 1)
  1. 二次调整后的逻辑缺陷:点击后直接将href属性替换为纯数字ID,丢失了固定的链接前缀,导致跳转地址无效,这版代码如下:
window.onclick = () => {
  document.querySelectorAll("a").forEach(link =>
    link.setAttribute("href", Math.floor(Math.random() * 111392.8) + 1)
  );
};

配套的原有HTML结构:

<title>
  Newgrounds Song Generator
</title>

<body>
  <h1>Click the button to visit a random song!</h1>
  <a href="https://www.newgrounds.com/audio/listen/" target="_blank">
    <button>Generate</button>
  </a>
正确实现代码

核心逻辑:每次点击时直接生成完整的链接字符串(固定前缀+新随机ID),完全不依赖当前href的现有值做拼接,从根源避免重复追加ID的问题;同时取消全局window点击绑定,只给生成按钮绑定事件,避免误触发。

<!DOCTYPE html>
<html>
<head>
  <title>Newgrounds Song Generator</title>
</head>
<body>
  <h1>Click the button to visit a random song!</h1>
  <a id="songLink" target="_blank">
    <button id="generateBtn">Generate</button>
  </a>

  <script>
    // 固定链接前缀抽为常量,后续调整地址只需修改这一处
    const AUDIO_BASE_PATH = "https://www.newgrounds.com/audio/listen/";
    const songLink = document.getElementById("songLink");
    const generateBtn = document.getElementById("generateBtn");

    // 页面首次加载时先生成一个初始链接,避免第一次点击前链接为空
    songLink.href = AUDIO_BASE_PATH + (Math.floor(Math.random() * 111393) + 1);

    generateBtn.addEventListener("click", () => {
      // 每次点击直接覆盖为全新的完整链接,不读取原有href值,彻底解决重复追加问题
      const newSongId = Math.floor(Math.random() * 111393) + 1;
      songLink.href = AUDIO_BASE_PATH + newSongId;
    });
  </script>
</body>
</html>
实现要点
  • 放弃「读取现有href再拼接内容」的逻辑,每次点击直接生成完整链接地址,从根本上杜绝多次点击重复叠加随机ID的问题
  • 移除全局window.onclick绑定,仅给生成按钮绑定点击事件,不会因为点击页面其他区域误修改链接
  • 通过ID直接定位目标歌曲链接,不需要遍历页面所有<a>标签,不会误改页面其他跳转链接,执行效率更高
  • 页面首次加载时就初始化第一个随机链接,避免按钮第一次点击前href为空的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 02:45:31