在Swiper JS场景下,实现跳转文件不存在时回退到索引页
解决Swiper画廊末尾跳转时的404回退问题
问题核心
你当前的try/catch方案无效,原因是:window.location.href跳转时,浏览器会直接离开当前页面加载目标URL,即便目标URL不存在(返回404),当前页面的JavaScript上下文已经终止,不会抛出可被捕获的异常,因此catch块永远不会执行。
可行解决方案
方案1:提前维护有效页面列表(最可靠)
因为你的画廊页面是本地托管的固定文件,直接定义所有有效画廊页面的文件名数组,跳转前先验证目标页面是否在列表内:
// 提前定义所有有效的画廊页面文件名(根据你的实际命名调整) const validGalleryPages = ["One.html", "Two.html", "Three.html"]; // 生成下一个有效页面路径 function getNextValidPage(currentPath) { const currentFileName = currentPath.split("/").pop(); // 建立文件名到序列序号的映射(根据你的命名规则调整) const pageOrder = { "One.html": 1, "Two.html": 2, "Three.html": 3 }; const currentIndex = pageOrder[currentFileName]; const nextIndex = currentIndex + 1; // 查找下一个有效文件名 const nextFileName = Object.keys(pageOrder).find(key => pageOrder[key] === nextIndex); return nextFileName ? nextFileName : "Index.html"; } // 在Swiper的reachEnd事件中调用 swiper.on('reachEnd', function() { const nextPage = getNextValidPage(window.location.pathname); window.location.href = nextPage; });
这个方案从根源避免了跳转无效URL的情况,完全不需要处理404回退。
方案2:预检查文件是否存在(适合动态序列)
如果你的画廊页面是数字序列命名(如1.html、2.html),可以通过HEAD请求预验证文件是否存在(仅适用于本地服务器托管,file://协议可能存在跨域限制):
// 检查文件是否存在的异步函数 function checkFileExists(url) { return new Promise(resolve => { const xhr = new XMLHttpRequest(); xhr.open('HEAD', url, true); xhr.onload = () => resolve(xhr.status >= 200 && xhr.status < 400); xhr.onerror = () => resolve(false); xhr.send(); }); } // Swiper事件处理逻辑 swiper.on('reachEnd', async function() { const currentFileName = window.location.pathname.split("/").pop(); // 提取文件名中的数字部分(适配数字序列命名) const numMatch = currentFileName.match(/(\d+)\.html/); if (!numMatch) { window.location.href = "Index.html"; return; } const nextNum = parseInt(numMatch[1]) + 1; const nextUrl = `${nextNum}.html`; const fileExists = await checkFileExists(nextUrl); window.location.href = fileExists ? nextUrl : "Index.html"; });
内容的提问来源于stack exchange,提问作者fishy
相关产品推荐
相关产品推荐

