如何用jQuery的find函数在父级.selectbox中定位对应.select-shows元素
解决同一父级选择框内的内容更新问题
你的核心问题是未精准定位当前点击选项所属的.selectbox容器,导致更新了页面上所有.select-shows元素。可以通过以下方式修正:
修正后的JavaScript代码
$(".option").click(function() { // 定位到当前选项所属的最外层.selectbox容器 const targetSelectBox = $(this).closest(".selectbox"); // 在该容器内找到对应的.select-shows元素 const selectBoxShow = targetSelectBox.find(".select-shows"); const optionTitle = $(this).find(".option-title").text(); selectBoxShow.text(optionTitle); });
原理说明
.closest(".selectbox"):从当前点击的.option元素开始向上遍历DOM树,找到第一个匹配.selectbox的祖先容器,精准锁定当前操作的选择框,避免影响其他选择框。- 后续使用
find(".select-shows")仅在锁定的容器内查找目标元素,确保只更新同一父级下的显示文本。
完整可运行代码示例
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"/> <div class="selectbox w-50 mb-5"> <div class="select"> <div> <i class="fa-light fa-grid-2"></i> <span class="select-shows">Select your City</span> </div> <i class="fas fa-angle-down"></i> </div> <menu class="options"> <div class="option"> <div class="option-container"> <i class="fas fa-angle-left"></i><span class="option-title">Whitehorse</span> </div> </div> <div class="option"> <div class="option-container"> <i class="fas fa-angle-left"></i><span class="option-title">Yellowknife</span> </div> </div> <div class="option"> <div class="option-container"> <i class="fas fa-angle-left"></i><span class="option-title">Regina</span> </div> </div> <div class="option"> <div class="option-container"> <i class="fas fa-angle-left"></i><span class="option-title">Winnipeg</span> </div> </div> <div class="option"> <div class="option-container"> <i class="fas fa-angle-left"></i><span class="option-title">Charlottetown</span> </div> </div> </menu> </div> <!-- 新增测试用选择框,验证互不干扰 --> <div class="selectbox w-50 mb-5"> <div class="select"> <div> <i class="fa-light fa-grid-2"></i> <span class="select-shows">Select your City</span> </div> <i class="fas fa-angle-down"></i> </div> <menu class="options"> <div class="option"> <div class="option-container"> <i class="fas fa-angle-left"></i><span class="option-title">Toronto</span> </div> </div> <div class="option"> <div class="option-container"> <i class="fas fa-angle-left"></i><span class="option-title">Vancouver</span> </div> </div> </menu> </div> <script> $(".option").click(function() { const targetSelectBox = $(this).closest(".selectbox"); const selectBoxShow = targetSelectBox.find(".select-shows"); const optionTitle = $(this).find(".option-title").text(); selectBoxShow.text(optionTitle); }); </script>
内容的提问来源于stack exchange,提问作者Darigan
相关产品推荐
相关产品推荐

