JavaScript:仅通过类名定位特定元素,实现点击.editPrice按钮仅显示对应.popupPriceContainer
解决点击
.editPrice按钮仅显示对应父容器内的.popupPriceContainer问题 问题分析
你当前的弹窗打开逻辑会把页面中所有.popupPriceContainer都显示出来,原因是遍历了所有该类名的元素并统一设置display:block。要实现仅显示当前按钮所在父容器内的弹窗,核心是通过点击的按钮定位到它所属的.position容器,再在这个容器范围内查找目标弹窗元素。
修改后的完整代码
HTML
<section id="serviceList" class="items"> <div class="position"> <button type="button" class="editPrice">Edit price</button> <div class="item"> Service 1 </div> <div class="price"> <span class="amount" id="priceElement">100</span> </div> <div class="popupPriceContainer"> <div class="popupPriceInner"> <input type="number" placeholder="100,00" class="priceInput"> <button value="Set Value" class="submbitPrice popupClose">Submit</button> <button class="popupClose">Close</button> </div> </div> </div> <div class="position"> <button type="button" class="editPrice">Edit price</button> <div class="item"> Service 2 </div> <div class="price"> <span class="amount">1000</span> </div> <div class="popupPriceContainer"> <div class="popupPriceInner"> <input type="number" placeholder="100,00" class="priceInput"> <button value="Set Value" class="submbitPrice popupClose">Submit</button> <button class="popupClose">Close</button> </div> </div> </div> <div class="position"> <button type="button" class="editPrice">Edit price</button> <div class="item"> Service 3 </div> <div class="price"> <span class="amount">240</span> </div> <div class="popupPriceContainer"> <div class="popupPriceInner"> <input type="number" placeholder="100,00" class="priceInput"> <button value="Set Value" class="submbitPrice popupClose">Submit</button> <button class="popupClose">Close</button> </div> </div> </div> </section>
CSS
#serviceList .position { margin-top: 16px; } .popupPriceContainer { display: none; }
JavaScript
// CLOSE POPUP PRICE CONTAINER const popupClose = document.getElementsByClassName('popupClose'); Array.from(popupClose).forEach((closeBtn) => { closeBtn.addEventListener('click', () => { // 2x .parentNode to select the outer wrapper closeBtn.parentNode.parentNode.style.display = "none"; }); }); // OPEN POPUP PRICE CONTAINER const popupEditPrice = document.getElementsByClassName('editPrice'); Array.from(popupEditPrice).forEach((editBtn) => { editBtn.addEventListener('click', () => { // 找到当前按钮所属的.position父容器 const parentContainer = editBtn.closest('.position'); // 在该容器内找到对应的.popupPriceContainer const targetPopup = parentContainer.querySelector('.popupPriceContainer'); // 仅显示这个弹窗 targetPopup.style.display = "block"; }); });
关键修改说明
- 定位父容器:使用
closest('.position')方法,从点击的.editPrice按钮出发,向上查找最近的拥有.position类的父元素,精准锁定当前按钮所在的容器。 - 查找目标弹窗:在找到的父容器内,用
querySelector('.popupPriceContainer')获取仅属于该容器的弹窗元素,避免影响页面其他同类型元素。 - 仅操作目标元素:只对找到的这个弹窗设置
display:block,完美实现点击按钮仅显示对应弹窗的需求。
内容的提问来源于stack exchange,提问作者Warkus
相关产品推荐
相关产品推荐

