计算类中的特定字符数(并将文本截断逻辑应用于该类的每个实例)

Count specific characters within a class (and apply text truncate logics to each instance of that class)

本文关键字:应用于 实例 字符 计算 文本      更新时间:2023-09-26

我有类似的HTML

<a href="/blabla" class="matchupLink">
    <span class="teams"> USA</span>
    <strong> -0 </strong>
    <span class="teams">Netherlands</span>
    <span class="pull-right dateOrScore"><strong>15 Jul</strong> : 3:00pm CST</span>
</a>
<a href="/blabla2" class="matchupLink">
    <span class="teams"> USA</span>
    <strong> -0 </strong>
    <span class="teams">Netherlands</span>
    <span class="pull-right dateOrScore"><strong>15 Jul</strong> : 3:00pm CST</span>
</a>
<a href="/blabla3" class="matchupLink">
    <span class="teams"> USA</span>
    <strong> -0 </strong>
    <span class="teams">Netherlands</span>
    <span class="pull-right dateOrScore"><strong>15 Jul</strong> : 3:00pm CST</span>
</a>

我想计算每个"matchupLink"类中的字符数,但不计算"dateOrScore"类中字符数。

如果字符数超过20个字符,我的目标是剪切文本并在字符20后面加上省略号,同时保留date(dateOrScore)元素。

我试过类似的东西

$('.matchupLink .teams').each(function () {
  console.log($(this).html())
});

但它单独返回每个teams元素,不能真正以这种方式使用省略号逻辑。

有什么想法吗?

感谢

Ps:我也尝试过获取所有文本,并排除"dateOrScore"(使用not()),但也失败了。

这就是您想要的吗?

var ellipses = 20;
$('.matchupLink').children().not('.dateOrScore').each(function() {
    var text = $(this).text();
    if(text.length > ellipses)
        $(this).text(text.substr(0, ellipses) + '...');
});