如何实现带搜索筛选的HTML下拉菜单并关联Google Sheets数据
解决搜索下拉菜单选中值更新按钮文本 + 导入Google Sheets数据问题
一、先修复「选中选项后更新按钮显示文本」的问题
原代码缺少下拉选项的点击事件处理,我们用事件委托实现功能,这种方式既能兼容静态选项,也能适配之后动态加载的Google Sheets数据:
修改后的完整代码:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .dropbtn { background-color: #04AA6D; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropbtn:hover, .dropbtn:focus { background-color: #3e8e41; } #myInput { box-sizing: border-box; background-image: url('searchicon.png'); background-position: 14px 12px; background-repeat: no-repeat; font-size: 16px; padding: 14px 20px 12px 45px; border: none; border-bottom: 1px solid #ddd; } #myInput:focus {outline: 3px solid #ddd;} .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f6f6f6; min-width: 230px; overflow: auto; border: 1px solid #ddd; z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown a:hover {background-color: #ddd;} .show {display: block;} </style> </head> <body> <h2>Search/Filter Dropdown</h2> <p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p> <div class="dropdown"> <button onclick="myFunction()" class="dropbtn">Dropdown</button> <div id="myDropdown" class="dropdown-content"> <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()"> <a href="#about">About</a> <a href="#base">Base</a> <a href="#blog">Blog</a> <a href="#contact">Contact</a> <a href="#custom">Custom</a> <a href="#support">Support</a> <a href="#tools">Tools</a> </div> </div> <script> /* 切换下拉菜单显示/隐藏 */ function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } /* 搜索筛选逻辑 */ function filterFunction() { var input, filter, div, a, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); div = document.getElementById("myDropdown"); a = div.getElementsByTagName("a"); for (i = 0; i < a.length; i++) { txtValue = a[i].textContent || a[i].innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { a[i].style.display = ""; } else { a[i].style.display = "none"; } } } /* 监听下拉选项点击,更新按钮文本 */ document.getElementById('myDropdown').addEventListener('click', function(e) { if (e.target.tagName === 'A') { const dropbtn = document.querySelector('.dropbtn'); // 更新按钮文本为选中的选项内容 dropbtn.textContent = e.target.textContent; // 关闭下拉菜单 this.classList.remove('show'); // 清空搜索框并重置选项显示状态 document.getElementById('myInput').value = ''; const allLinks = this.getElementsByTagName('a'); for (let i = 0; i < allLinks.length; i++) { allLinks[i].style.display = ''; } // 阻止默认锚点跳转 e.preventDefault(); } }); </script> </body> </html>
关键修改说明:
- 新增下拉内容的点击事件监听,通过
e.target.tagName判断点击对象是否为选项链接 - 点击后自动更新按钮文本、关闭菜单、清空搜索框并重置选项显示
- 调用
e.preventDefault()阻止标签的默认跳转行为(不需要跳转可保留)
二、导入Google Sheets A列数据到下拉菜单
要加载Google Sheets A1:A区域的姓名数据,需先将表格发布为公开可访问的CSV,步骤如下:
- 打开目标Google Sheets表格
- 右上角「分享」→ 设置权限为「Anyone with the link can view」
- 「文件」→「分享」→「发布到网页」→ 选择对应工作表、「CSV」格式,点击「发布」并复制生成的CSV链接
在之前的代码中添加数据加载逻辑,将以下代码插入到<script>标签末尾:
/* 从Google Sheets加载姓名数据 */ function loadNamesFromSheets() { // 替换成你自己的Google Sheets发布CSV链接 const csvUrl = 'https://docs.google.com/spreadsheets/d/e/[你的发布ID]/pub?output=csv'; fetch(csvUrl) .then(response => { if (!response.ok) throw new Error('数据加载失败'); return response.text(); }) .then(csvText => { // 解析CSV内容,过滤空行 const rows = csvText.split('\n').filter(row => row.trim() !== ''); const dropdownContent = document.getElementById('myDropdown'); // 移除原有静态选项(保留搜索框) const existingLinks = dropdownContent.querySelectorAll('a'); existingLinks.forEach(link => link.remove()); // 循环生成新的选项链接 rows.forEach(row => { const name = row.trim(); if (name) { const a = document.createElement('a'); a.href = '#'; a.textContent = name; dropdownContent.appendChild(a); } }); }) .catch(error => console.error('加载Google Sheets数据出错:', error)); } // 页面加载完成后自动加载数据 window.onload = loadNamesFromSheets;
注意事项:
- 确保Google Sheets权限设置正确,否则会出现跨域或权限错误
- 若表格有表头(A1是标题),可修改
rows为rows.slice(1)跳过第一行 - 公开CSV一般不会有跨域问题,若遇到问题可检查发布设置或使用Google Apps Script中转
内容的提问来源于stack exchange,提问作者Elanu
相关产品推荐
相关产品推荐

