我想将字符限制转换为字数限制,因为它会在我的段落中的某些字词中途中断,但我不确定要添加/更改的内容。
$(document).ready(function() {
var nInitialCount = 180; //Intial characters to display
var moretext = "Read more >";
var lesstext = "Read less";
$('.longtext').each(function() {
var paraText = $(this).html();
if (paraText.length > nInitialCount) {
var sText = paraText.substr(0, nInitialCount);
var eText = paraText.substr(nInitialCount, paraText.length - nInitialCount);
var newHtml = sText + '<span class="moretext"><span>' + eText + '</span><a href="" class="links">' + moretext + '</a></span>';
$(this).html(newHtml);
}
});
$(".links").on('click', function(e) {
var lnkHTML = $(this).html();
if (lnkHTML == lesstext) {
$(this).html(moretext);
} else {
$(this).html(lesstext);
}
$(this).prev().toggle();
e.preventDefault();
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="longtext">
Text here<br>
<br> Text here as well<br>
<br> More Text here
</div>
<button class="links">Read less</button>
&#13;
任何帮助都将不胜感激。