-1

如何修剪字符串宽度,使其不超过 20 个字符,包括空格和 ... 到字符串的末尾?

<p class="streetname">Galloway Road, Bishop's Stortford</p>

有没有一个jQuery方法呢?

4

2 回答 2

0

您可以substr()对该段落文本的字符串值使用函数:

var text = $('.streetname').text();
var newText = text.substr(0,17) + '...';
$('.streetname').text(newText)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="streetname">Galloway Road, Bishop's Stortford</p>

于 2018-07-17T11:54:49.070 回答
0

你可以这样做:

if ($(".streetname").text().length > 20) {         
    $(".streetname").text($(".streetname").text().substring(0,50) + '...');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="streetname">This text is way to long to be displayed on the site so we just short it with jquery</p>

但是,如果您从 php 收到文本,您也可以在那里短它..

于 2018-07-17T11:56:20.317 回答