JS实现单链接循环打开关闭(30-40秒间隔)及URL生成问题
修正剧集链接循环打开/关闭的问题
问题根源
你的代码中,第一段的allURL数组通过episodeLinks.join("")把所有生成的链接拼接成了单个超长无效字符串,导致循环打开的是这个拼接后的错误地址,而非独立的有效链接。
修正后的完整代码
// 自动生成剧集链接 const seasons = document.querySelectorAll("#season li"); const episodes = document.querySelectorAll("#episode li"); let $prak = '1', episodeLinks = []; seasons.forEach(seasonLi => { const season = seasonLi.textContent.trim(); episodes.forEach(episodeLi => { const episode = episodeLi.textContent.trim(); const url = `https://www.test.com/watch/${$prak}/season/${season}/episode/${episode}`; episodeLinks.push(url); }); }); // 循环打开并关闭窗口 function showUrl(index = 0) { if (episodeLinks.length === 0 || index < 0 || index >= episodeLinks.length) { return; } const popup = window.open(episodeLinks[index]); // 30-40秒后关闭窗口,继续下一个链接(这里设为35秒,可自行调整) setTimeout(() => { popup.close(); showUrl(index + 1); }, 35000); } showUrl();
关键修改点
- 移除了
allURL变量的错误用法:直接使用生成好的episodeLinks数组(每个元素都是独立的有效URL),无需用join("")拼接。 - 简化逻辑:删除多余的中间变量,让代码更直接。
- 可自定义超时时间:把
setTimeout的第二个参数改成30000(30秒)到40000(40秒)之间的数值即可。 - 优化语法:使用ES6默认参数和箭头函数,提升代码可读性。
内容的提问来源于stack exchange,提问作者kfir ben shimon
相关产品推荐
相关产品推荐

