使用 javascript substring() 创建阅读更多链接

2022-01-16 00:00:00 asp-classic jquery javascript

我正在开发一个经典 ASP 页面,它从数据库中提取一些内容并在前 100 个字符之后创建一个阅读更多链接,如下所示;

I'm developing a Classic ASP page that pulls some content from a database and creates a Read more link after the first 100 characters as follows;

<div class="contentdetail"><%=StripHTML(rspropertyresults.Fields.Item("ContentDetails").Value)%></div>

<script type="text/javascript">
    $(function() {

        var cutoff = 200;
        var text = $('div.contentdetail').text();
        var rest = $('div.contentdetail').text().substring(cutoff);
        if (text.length > 200) {
          var period = rest.indexOf('.');
          var space = rest.indexOf(' ');
          cutoff += Math.max(Math.min(period, space), 0);
        }

        var visibleText = $('div.contentdetail').text().substring(0, cutoff);

        $('div.contentdetail')
            .html(visibleText + ('<span>' + rest + '</span>'))
            .append('<a title="Read More" style="font-weight:bold;display: block; cursor: pointer;">Read More&hellip;</a>')
            .click(function() {
                $(this).find('span').toggle();
                $(this).find('a:last').hide();
            });

        $('div.contentdetail span').hide();
    });
</script>

但是,脚本显然只是在 100 个字符后截断了文本.最好我希望它继续写文本,直到第一个句号或空格,例如.这可以吗?

However, the script obviously just cuts the text off after 100 characters. Preferably I would like it to keep on writing text until the first period or space, for example. Is this possible to do?

谢谢.

推荐答案

var cutoff = 100;
var text = $('div.contentdetail').text();
var rest = text.substring(cutoff);
if (text.length > cutoff) {
  var period = rest.indexOf('.');
  var space = rest.indexOf(' ');
  cutoff += Math.max(Math.min(period, space), 0);
}
// Assign the rest again, because we recalculated the cutoff
rest = text.substring(cutoff);
var visibleText = $('div.contentdetail').text().substring(0, cutoff);

稍微缩短了一点.编辑:修复了一个错误编辑:生活质量改善

shortened it a bit. EDIT: Fixed a bug EDIT: QoL improvement

相关文章