我有一個幾乎完成的腳本,但我無法弄清楚最後一點在這裏。該腳本旨在限制可以輸入到文本區域中的單詞的數量,並且如果它們超過了單詞限制,則會刪除這些額外的單詞。我有超過最大標記爲超額的字數。例如,如果您要輸入102個單詞,那麼過量將是2.如何從文本區域移除這兩個單詞?從文本框中刪除多餘的單詞
jQuery(document).ready(function($) {
var max = 100;
$('#text').keyup(function(e) {
if (e.which < 0x20) {
return;
}
var value = $('#text').val();
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
if (wordCount == max) {
// Reached max, prevent additional.
e.preventDefault();
} else if (wordCount > max) {
<!--Edited to show code from user3003216-->
<!--Isn't working like this, textarea doesn't update.-->
var overage = wordCount - max;
var words = value.split(' ');
for(var i = 0; i<overage; i++){
words.pop();
}
}
});
});
順便說一句,jQuery提供了[微調功能(http://api.jquery.com/jquery.trim/):'$ .trim()'。 – royhowie