如何依据title元素长度动态限制或隐藏description元素文本?
批量处理title与description元素的显示逻辑
原始HTML结构
<div class="Main"> <div class="About_Sports"> <div class="sportsPhoto"> <div class="content"> <div class="location"> <div class="title">Badminton is a racquet sport played using racquets to hit a shuttlecock across a net. Although it may be played with larger teams</div> <div class="description">Games employing shuttlecocks have been played for centuries across Eurasia,[a] but the modern game of badminton developed in the mid-19th century among the expatriate officers of British India as a variant of the earlier game of battledore and shuttlecock. ("Battledore" was an older term for "racquet".)[4] Its exact origin remains obscure. The name derives from the Duke of Beaufort's Badminton House in Gloucestershire,[5] but why or when remains unclear.</div> </div> </div> </div> <div class="sportsPhoto"> <div class="content "> <div class="location"> <div class="title">Tennis is a racket sport that is played either individually against a single opponent (singles) or between two teams of two players each (doubles).</div> <div class="description">The four marquee tennis tournaments every year, the Grand Slams - Australian Open, French Open, Wimbledon and the US Open - provide high-quality action throughout the year in addition to various lower-level tournaments to keep fans engaged.</div> </div> </div> </div> </div> </div>
需求说明
针对每个.description元素:
- 若同级的
.title文本长度等于10字符,将.description的文本截断至20字符 - 若同级的
.title文本长度超过10字符,将.description设置为display: none
错误尝试代码
if ($(".About_Sports.sportsPhoto.content.location").length > 0) { if($(this).closest('.title').children('.description')){ } }
正确实现方案
通过遍历每个包含title和description的容器,逐个处理逻辑即可:
// 遍历所有包含标题和描述的location容器 $('.About_Sports .location').each(function() { const $title = $(this).find('.title'); const $description = $(this).find('.description'); // 去除文本两端空白,计算真实长度 const titleLength = $.trim($title.text()).length; if (titleLength > 10) { // 标题长度超10,隐藏描述 $description.hide(); } else if (titleLength === 10) { // 标题长度等于10,截断描述文本到20字符 const descText = $.trim($description.text()); const truncatedText = descText.length > 20 ? descText.slice(0, 20) + '...' : descText; $description.text(truncatedText); } // 若需处理标题长度小于10的情况,可补充else分支 });
代码说明
- 遍历独立容器:用
.each()遍历每个.location,确保每组title和description单独处理,避免跨容器干扰 - 精准获取元素:在当前容器内查找对应的title和description,保证操作对象准确
- 准确计算长度:用
$.trim()去除文本两端的空白字符,避免换行、空格影响长度计算结果 - 逻辑分支处理:
- 标题长度>10:直接调用
hide()设置display: none - 标题长度=10:截断描述文本到20字符,超出部分添加省略号(可根据需求调整)
- 标题长度>10:直接调用
内容的提问来源于stack exchange,提问作者user25502092
相关产品推荐
相关产品推荐

