如何从包含两个单词的类名的普通html段落中截断最后20个字符?例如<p class="sentence slice">Last twenty characters have to be chopped off!!!</p>
我知道JS https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice中有一个slice方法,但是如何在网站上实现呢?
最佳答案
如果您对使用.slice
感兴趣,则只需执行以下操作:
的JavaScript
$("#clickme").click(function () {
var text = $("p").text();
text = (text.length > 20) ? text.slice(0,-20) : text;
// important to check whether the text is longer than 20 characters
$("p").text(text); // update the text
})
的HTML
<p>Lots and lots and lots and lots and lots of text12345678901234567890</p>
<button id="clickme">remove last 20 characters</button>
fiddle
关于javascript - 用JS chop HTML段落中的最后一个字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24844585/