多Read More按钮仅响应首个元素的问题解决咨询
解决多个“Read More”按钮仅控制首个元素的问题
你的问题根源是HTML中ID属性必须唯一,getElementById()方法只会返回页面中第一个匹配该ID的元素,所以所有按钮都只能操控第一组内容。下面是具体的修复方案:
步骤1:替换重复ID为类
把HTML中重复的id属性改成class,因为类允许在多个元素上复用:
<div class="quote__box__text"> lorem ipsum <span class="dots">...</span> <span class="more">Lorem ipsum</span> <button class="read-more-btn">Read more</button> </div> <div class="quote__box__text"> lorem ipsum <span class="dots">...</span> <span class="more">Lorem ipsum</span> <button class="read-more-btn">Read more</button> </div>
步骤2:修改JS逻辑,实现分组控制
通过按钮的父容器定位对应元素,确保每个按钮只操作自己所在组内的内容:
// 给所有按钮绑定点击事件 document.querySelectorAll('.read-more-btn').forEach(btn => { btn.addEventListener('click', function() { // 获取当前按钮所在的父容器 const container = this.closest('.quote__box__text'); // 在容器内查找对应的元素 const dots = container.querySelector('.dots'); const moreText = container.querySelector('.more'); if (dots.style.display === 'none') { dots.style.display = 'inline'; this.textContent = 'Przeczytaj więcej'; moreText.style.display = 'none'; } else { dots.style.display = 'none'; this.textContent = 'Zwiń'; moreText.style.display = 'inline'; } }); });
优化建议:用CSS初始化隐藏状态
为了避免页面加载时“更多内容”短暂显示,直接用CSS默认隐藏.more元素:
.more { display: none; }
关键说明
this.closest('.quote__box__text'):精准定位当前按钮所在的父容器,确保操作范围不超出当前组container.querySelector:只在当前容器内查找目标元素,避免全局查找导致的错误匹配
内容的提问来源于stack exchange,提问作者Nibirian
相关产品推荐
相关产品推荐

