問(wèn)題描述
我正在開(kāi)發(fā)一個(gè)經(jīng)典 ASP 頁(yè)面,它從數(shù)據(jù)庫(kù)中提取一些內(nèi)容并在前 100 個(gè)字符之后創(chuàng)建一個(gè)閱讀更多鏈接,如下所示;
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…</a>')
.click(function() {
$(this).find('span').toggle();
$(this).find('a:last').hide();
});
$('div.contentdetail span').hide();
});
</script>
但是,腳本顯然只是在 100 個(gè)字符后截?cái)嗔宋谋?最好我希望它繼續(xù)寫(xiě)文本,直到第一個(gè)句號(hào)或空格,例如.這可以嗎?
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);
稍微縮短了一點(diǎn).編輯:修復(fù)了一個(gè)錯(cuò)誤編輯:生活質(zhì)量改善
shortened it a bit. EDIT: Fixed a bug EDIT: QoL improvement
這篇關(guān)于使用 javascript substring() 創(chuàng)建閱讀更多鏈接的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!