jQuery实现Read more按钮时如何让e.preventDefault对more_content ID生效
解决方案
核心优化点
- 用属性前缀选择器同时匹配所有
readmore_开头的按钮和more_content_开头的内容块,一次性绑定点击事件,e.preventDefault会对两类元素都生效 - 自动提取ID后缀匹配对应按钮和内容块,不用重复写多段几乎完全相同的JS代码
- 修复原有HTML中内容段落默认隐藏的问题,保证展开后能正常看到内容
修改后代码
JS代码
把原有多段按钮绑定代码替换为下面的代码即可:
// 同时为readmore系列按钮和more_content系列内容块绑定点击事件 $("[id^='readmore_'], [id^='more_content_']").click(function(e) { e.preventDefault(); // 提取ID后缀匹配对应元素 const idSuffix = $(this).attr("id").split("_").pop(); const $targetContent = $(`#more_content_${idSuffix}`); const $targetBtn = $(`#readmore_${idSuffix}`); // 切换内容显隐 $targetContent.toggle("fast"); window.scrollTo(170, 170); // 切换按钮文本 const btnText = $targetBtn.text().trim(); $targetBtn.text(btnText === "Read more" ? "Read less" : "Read more"); });
HTML修改说明
找到所有more_content_开头的元素,把内部p标签的style="display:none"内联样式删除,否则内容展开后也不可见,修改后示例如下:
<div class="more_content_01" id="more_content_01"> <p>Das ist mehr content</p> </div>
可选CSS优化
你当前CSS中.toggleBtn_01和.toggleBtn_02的样式完全重复,可以合并为一个通用类减少冗余代码:
.toggleBtn { cursor: pointer; color: #ff7c26; font-size: 115%; user-select: none; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; } .toggleBtn:hover { color: white; }
之后把HTML中toggleBtn_01、toggleBtn_02的类名都替换为toggleBtn即可。
内容的提问来源于stack exchange,提问作者Question__
相关产品推荐
相关产品推荐

