实现类似Booking.com的多选下拉框遇问题,求技术指导
问题描述
我希望实现一个功能与Booking.com网站上类似的下拉框(已附上截图),但在开发过程中遇到了问题,无法定位错误原因,请问您有什么解决建议吗?
我的代码
HTML
<div class="dropdown"> <input type="text" id="droptxt" class="list" readonly placeholder="Number of guests"> <div id="content" class="content"> <div class="list"> <input type="checkbox" id="rooms" class="list" value="Choose how many rooms" /> <label for="rooms" class="list">Choose how many rooms </label> <input type="hidden" class="list quantity" min="1" value="1" /> </div> <div class="list"> <input type="checkbox" id="adults" class="list" value="Choose the number of adults" /> <label for="adults" class="list">Choose the number of adults </label> <input type="hidden" class="list quantity" min="1" value="1" /> </div> <div class="list"> <input type="checkbox" id="children" class="list" value="Choose the number of children" /> <label for="children" class="list">Choose the number of children </label> <input type="hidden" class="list quantity" min="1" value="1" /> </div> </div> </div>
JavaScript
const txt = document.getElementById('droptxt'); const content = document.getElementById('content'); const checkboxes = document.querySelectorAll('.list input[type="checkbox"]'); const quantity = document.querySelectorAll('.quantity'); txt.addEventListener('click', function() { content.classList.toggle('show'); }); // Close the dropdown if the user clicks outside of it window.onclick = function(e) { if (!e.target.closest('.dropdown')) { content.classList.remove('show'); } }; checkboxes.forEach(function(checkbox, index) { checkbox.addEventListener('click', function() { quantity[index].type = checkbox.checked ? 'number' : 'hidden'; calc(); }); }); quantity.forEach(function(input) { input.addEventListener('input', calc); }); // 初始化渲染状态 calc(); function calc() { let arr = []; for (let i = 0; i < checkboxes.length; i++) { if (checkboxes[i].checked) { arr.push(`${quantity[i].value} x ${checkboxes[i].value}`); } } txt.value = arr.length > 0 ? arr.join(', ') : ''; }
解决建议
- Label关联错误:原HTML中
label的for属性错误绑定了checkbox的value,正确应该对应checkbox的id(比如for="rooms"而非for="Choose how many rooms"),否则点击标签无法触发复选框状态切换。 - 数量输入框选择器失效:原JS用
input[type="number"]选择数量框,但初始状态这些输入框是hidden类型,导致页面加载时无法选中。改为通过quantity类选择,确保无论输入框类型如何都能获取到元素。 - 外部点击关闭逻辑缺陷:原判断
!e.target.matches('.list')会导致点击下拉框内的任何.list元素时关闭下拉,改为用e.target.closest('.dropdown')判断点击目标是否在下拉容器内,不在才执行关闭操作。 - 缺失初始状态渲染:页面加载后未调用
calc(),导致输入框初始为空,添加初始调用后能默认显示选中项的内容。 - 补充必要CSS:需要添加基础样式控制下拉框的显示隐藏,示例如下:
.content { display: none; position: absolute; background-color: #fff; border: 1px solid #ddd; padding: 10px; margin-top: 5px; } .content.show { display: block; } .dropdown { position: relative; display: inline-block; } #droptxt { padding: 8px 12px; cursor: pointer; border: 1px solid #ddd; border-radius: 4px; }
内容的提问来源于stack exchange,提问作者Emanuel Jr Mogosan
相关产品推荐
相关产品推荐

