JavaScript:如何根据用户选择动态设置索引?问题求助
问题分析
- 首页有6个按钮,每个按钮跳转至带“Discover”按钮的第二页,预期每个Discover按钮对应特定视频链接,但目前所有点击都固定使用索引0,问题根源:
solutions数组仅初始化了一个空对象,没有对应6个项目的有效URL数据- 首页的按钮选择索引未传递到第二页,导致第二页无法识别用户选中的是首页第几个按钮
解决方案
1. 首页传递选中索引到第二页
首页每个跳转按钮需要把自身索引传递给第二页,最简单的方式是通过URL参数:
<!-- 首页6个跳转按钮示例 --> <button onclick="window.location.href='second-page.html?index=0'">按钮1</button> <button onclick="window.location.href='second-page.html?index=1'">按钮2</button> <button onclick="window.location.href='second-page.html?index=2'">按钮3</button> <button onclick="window.location.href='second-page.html?index=3'">按钮4</button> <button onclick="window.location.href='second-page.html?index=4'">按钮5</button> <button onclick="window.location.href='second-page.html?index=5'">按钮6</button>
2. 第二页接收索引并绑定对应逻辑
第二页先从URL获取首页传来的索引,再给Discover按钮绑定正确的视频加载逻辑,同时完善solutions数组:
// 完善solutions数组,对应6个项目的视频URL const solutions = [ { url: "https://example.com/video1" }, { url: "https://example.com/video2" }, { url: "https://example.com/video3" }, { url: "https://example.com/video4" }, { url: "https://example.com/video5" }, { url: "https://example.com/video6" } ]; // 从URL参数中获取首页传递的索引 function getSelectedIndex() { const urlParams = new URLSearchParams(window.location.search); const index = urlParams.get('index'); // 确保索引是有效数字,默认0 return index !== null ? parseInt(index) : 0; } const selectedIndex = getSelectedIndex(); // 给所有Discover按钮绑定点击事件,使用获取到的索引 document.querySelectorAll('.discover-button').forEach(button => { button.addEventListener('click', () => { const videoIframe = document.getElementById('videoIframe'); // 检查索引是否在solutions数组范围内,避免报错 if (selectedIndex >= 0 && selectedIndex < solutions.length) { videoIframe.src = solutions[selectedIndex].url; document.getElementById('iframeContainer').style.display = 'block'; } }); }); // 关闭iframe的函数保持不变 function closeIframe() { const videoIframe = document.getElementById('videoIframe'); videoIframe.src = ''; document.getElementById('iframeContainer').style.display = 'none'; }
替代方案(单页应用场景)
如果是单页应用(无需页面跳转),可以用localStorage传递索引:
// 首页按钮点击时存储索引 document.querySelectorAll('.home-button').forEach((button, index) => { button.addEventListener('click', () => { localStorage.setItem('selectedSolutionIndex', index); // 切换到第二页组件 }); }); // 第二页读取索引 const selectedIndex = parseInt(localStorage.getItem('selectedSolutionIndex')) || 0;
内容的提问来源于stack exchange,提问作者Asser
相关产品推荐
相关产品推荐

