jQuery:仅选中被点击元素,实现展开更多功能
嘿,这个需求我之前做项目也碰到过,咱们可以用两种方式实现,确保每个「read more」只触发它对应的隐藏内容,不会影响其他模块:
方案1:原生JavaScript实现
这个方案不需要依赖任何库,纯原生代码就能搞定,兼容性也很好。
思路
- 给所有的
.showMore按钮绑定点击事件 - 点击时,先阻止a标签默认的跳转行为(不然点一下会跳到页面顶部)
- 找到当前按钮紧挨着的前一个
.dataShow元素,切换它的显示状态 - 顺便可以把按钮文字从「read more」改成「read less」,提升用户体验
完整代码
<!-- 你的HTML结构,我稍微整理了一下 --> <div class="dataShow" style="display: none">Data 1 ...</div> <a href="#" class="showMore">read more</a> <div class="dataShow" style="display: none">Data 2 ...</div> <a href="#" class="showMore">read more</a> <div class="dataShow" style="display: none">Data 3 ...</div> <a href="#" class="showMore">read more</a> <script> // 获取所有showMore按钮 const showMoreButtons = document.querySelectorAll('.showMore'); showMoreButtons.forEach(button => { button.addEventListener('click', function(e) { // 阻止默认跳转行为 e.preventDefault(); // 找到当前按钮前面的dataShow元素 const targetData = this.previousElementSibling; // 切换显示/隐藏状态 if (targetData.style.display === 'none') { targetData.style.display = 'block'; this.textContent = 'read less'; } else { targetData.style.display = 'none'; this.textContent = 'read more'; } }); }); </script>
方案2:jQuery实现(如果项目已引入jQuery)
如果你的项目已经用了jQuery,代码会更简洁,逻辑和原生的一致:
完整代码
<!-- 同样的HTML结构 --> <div class="dataShow" style="display: none">Data 1 ...</div> <a href="#" class="showMore">read more</a> <div class="dataShow" style="display: none">Data 2 ...</div> <a href="#" class="showMore">read more</a> <div class="dataShow" style="display: none">Data 3 ...</div> <a href="#" class="showMore">read more</a> <script> $('.showMore').on('click', function(e) { e.preventDefault(); // 用prev()方法直接获取前一个兄弟元素 const $targetData = $(this).prev('.dataShow'); $targetData.toggle(); // 切换按钮文字 $(this).text($targetData.is(':visible') ? 'read less' : 'read more'); }); </script>
注意事项
- 确保你的HTML结构里,每个
.showMore按钮直接紧跟在对应的.dataShow元素后面,这样previousElementSibling或者prev()才能准确找到目标元素 - 如果后续要修改结构,比如在dataShow和showMore之间加了其他元素,那就要调整选择器,比如用
previousElementSibling.previousElementSibling或者jQuery的prevAll('.dataShow').first()来找到最近的那个dataShow元素
内容的提问来源于stack exchange,提问作者user9511123
相关产品推荐
相关产品推荐

