Shuffle按钮跳转随机HTML文件的问题及解决方案
实现Shuffle按钮随机跳转功能
我已经实现了JavaScript Shuffle按钮功能,但当前点击该按钮只能跳转到document.location.href指定的固定URL(示例为somefile.html)。现在同文件夹下有350余个其他.html文件,我希望点击Shuffle按钮时能随机跳转至其中一个。
解决方案
保留原按钮中document.location.href = 'somefile.html'的设置,在somefile.html中添加URL列表定义和随机跳转逻辑,用户访问该文件时会自动跳转到列表中的随机URL:
// 定义所有需要随机跳转的HTML文件路径 var RedirectURLs = { "urls" : [ { "url" : "1.html" }, { "url" : "2.html" }, { "url" : "3.html" }, // 继续添加剩余350+个文件的路径,格式统一为 { "url" : "文件名.html" } ] } // 随机跳转函数 function randomRedirect() { const urlList = RedirectURLs.urls; // 生成0到urlList长度-1之间的随机整数 const randomIdx = Math.floor(Math.random() * urlList.length); // 跳转到随机选中的URL window.location.href = urlList[randomIdx].url; } // 页面加载完成后执行跳转 window.addEventListener('load', randomRedirect);
原Shuffle按钮代码
jQuery('body').on('click', '#shuffle-button', function() { gtag('event', 'Shuffle', { 'click': 'true' }); ga('send', 'event', 'Shuffle', 'click', 'true'); document.location.href = 'somefile.html'; }).on('click', '#station-share-toggle, #station-share-close', function() { $('#station-share-buttons').toggle(); }).on('click', '.jp-share-button', function() { window.open($(this).attr('href'), "share", "width=500, height=500"); return false; });
内容的提问来源于stack exchange,提问作者ShoutCast Media
相关产品推荐
相关产品推荐

