为什么JavaScript的closest方法找不到对应li元素?
现象说明
closest() 方法的常规逻辑为:沿DOM树向上搜索,查找与指定CSS选择器匹配的最近元素。
实际运行中观察到的异常表现:
- 当点击两个
li元素之间的margin空隙区域时,e.target.closest('.amenity_id')返回null,无法执行后续的交互逻辑 - 如果将样式中的
margin-bottom: 15px;替换为padding-bottom,所有交互逻辑可正常运行
触发问题的样式片段
.amenities-filters-inner ul li{ margin-bottom: 15px; }
问题触发位置
点击下图红色标记的空隙区域时,无法定位到对应的li元素:
完整关联代码实现
交互逻辑JS代码
document.querySelectorAll(".amenities-filters-inner ").forEach(function(item){ item.addEventListener("click",function(e){ e.preventDefault(); let element = null; element = e.target.closest(".amenity_id"); // element = e.target.querySelector(".amenity_id"); element = element.children[0].children[1]; element.checked == true ? element.checked = false : element.checked =true; let dataId = + element.getAttribute('data-id'); console.log(element) console.log(dataId) }) })
全量关联CSS代码
.amenities-filters-inner{ border: 2px dashed royalblue; max-width: 300px; padding: 1rem; } ul{ list-style: none; width: 100%; margin: 0; padding: 0; } li{ border: 2px solid rgb(133, 129, 129); padding: 3px; } .amenities-filters-inner:last-child{ margin-bottom: 0; } .amenities-filters-inner ul li{ margin-bottom: 20px; } .amenities-filters-inner ul li:last-child{ margin-bottom: 0; } .check { display: flex; align-items: center; justify-content: space-between; position: relative; padding-left: 31px; margin-bottom: 0; padding-right: 0; cursor: pointer; font-size: 14px; color: #646464; } .check strong{ color: #969696; font-size: 14px; font-weight: 400; } .check input { position: absolute; opacity: 0; cursor: pointer; } .checkmark { position: absolute; top: 0; left: 0; height: 17px; width: 17px; background-color: #fff ; border-color: #646464; border-style:solid; border-width:1px; border-radius: 2px; } .check input:checked ~ .checkmark { background-color: #fff; border-color: #007FEB; } .checkmark:after { content: ""; position: absolute; display: none; } .check input:checked ~ .checkmark:after { display: block; } .check .checkmark:after { left: 5px; top: 1px; width: 5px; height: 10px; border: solid ; border-color:#007FEB; border-width: 0 2px 2px 0; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); }
页面HTML结构
<div class="amenities-filters-inner"> <ul> <li class="amenity_id"> <label class="check ">One <strong>One</strong> <input type="checkbox" class="amenity_data" data-id="1" name="is_name"> <span class="checkmark"></span> </label> </li> <li class="amenity_id"> <label class="check ">Two <strong>Two</strong> <input type="checkbox" class="amenity_data" data-id="2" name="is_name"> <span class="checkmark"></span> </label> </li> <li class="amenity_id"> <label class="check ">Three<strong>Three</strong> <input type="checkbox" class="amenity_data" data-id="3" name="is_name"> <span class="checkmark"></span> </label> </li> </ul> </div>
内容的提问来源于stack exchange,提问作者نور
相关产品推荐
相关产品推荐

