2014-07-19 52 views
0

我有一個幾乎完成的腳本,但我無法弄清楚最後一點在這裏。該腳本旨在限制可以輸入到文本區域中的單詞的數量,並且如果它們超過了單詞限制,則會刪除這些額外的單詞。我有超過最大標記爲超額的字數。例如,如果您要輸入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(); 
      } 

     } 
    });   
}); 
+0

順便說一句,jQuery提供了[微調功能(http://api.jquery.com/jquery.trim/):'$ .trim()'。 – royhowie

回答

0

最簡單的方法就是計算keypress上的字數並從那裏開始。檢查是否有更多的單詞超過允許的數量。如果是這樣,請刪除所有多餘的單詞:while (text.length > maxWords)。然後,只需將文本框的值替換爲更新的文本。

fiddle

的JavaScript

var maxWords = 10; 
$("#myText").keypress(function (event) { 
    var text = $(this).val().split(" "); // grabs the text and splits it 
    while (text.length > maxWords) {  // while more words than maxWords 
     event.preventDefault(); 
     text.pop(); // remove the last word 
     // event.preventDefault() isn't absolutely necessary, 
     // it just slightly alters the typing; 
     // remove it to see the difference 
    } 
    $(this).val(text.join(" ")); // replace the text with the updated text 
}) 

HTML

<p>Enter no more than 10 words:</p> 
<textarea id="myText"></textarea> 

CSS

textarea { 
    width: 300px; 
    height: 100px;  
} 

您可以通過粘貼超過maxWords(在這種情況下爲10-字符到textarea並按空格)輕鬆測試它是否正常工作。所有額外的單詞將被刪除。

+0

哦,哇,這太簡單了,那麼我是試圖去做。非常感謝!哦,順便說一句,你離開了一個;在最後。 – user1727423

+0

@ user1727423哪裏?你是指'$(「#myText」).presspress()'塊的結尾嗎?在那裏,或者在任何地方,分號並不是必需的,對於這個問題(除了for循環)。 – royhowie

+0

分隔語句和方法調用(如調用'keypress')需要分號,但不適用於函數定義。 JS解釋器並不在意,如果你把它放在行尾,但是如果你的JS文件被縮小了(在部署到Prod服務器的時候很多),那麼刪除空白以減小文件大小。然後,由於缺少分號,您的代碼會產生語法錯誤。 – nbrooks

0

以及它會更好,所以這裏使用Java腳本你去:

var maxWords = 20; 
event.rc = true; 
var words = event.value.split(" "); 
if (words.length>maxWords) { 
    app.alert("You may not enter more than " + maxWords + " words in this field."); 
    event.rc = false; 
} 
+0

我對使用提醒沒有興趣。我的目標是最大限度地刪除額外的單詞。不提醒它已超過最大值。 – user1727423

0

你可以把下面的代碼到您的else if聲明..

else if (wordCount > max) { 
    var overage = wordCount - max; 
    var words = value.split(' '); 
    for(var i = 0; i<overage; i++){ 
     words.pop(); 
    } 
} 

如果你想從words得到您的字符串,您可以使用join,如下所示:

str = words.join(' '); 
+0

這對我來說並不真正有效。我玩弄它,我只是不明白如何將修改後的文本回到文本區域。我將你的代碼添加到原始文章中,以顯示我如何放置它。我嘗試了str = words.join('');這對我來說似乎沒有任何作用。 – user1727423

+0

嗯..如果你真的比較我的答案和@luxelin,你可以看到兩者都使用'.pop()'和'.join()'..也許你說什麼都沒有改變,因爲在我的回答中,我把它放入變量'str',而不是'textarea'就是這樣,'$('#text')。val(words.join());'.. –

0

jsFiddle Demo

您可以使用val重新值文本框。數組slice方法將允許您從數組中拉出前100個單詞。然後加入一個空格,然後將它們粘在文本框中。

$(document).ready(function($) { 
    var max = 100; 

    $('#text').keyup(function(e) { 

     if (e.which < 0x20) { 
      return; 
     } 

     var value = $('#text').val(); 
     var words = value.trim().split(/\s+/gi); 
     var wordCount = words.length; 

     if (wordCount == max) { 
      // Reached max, prevent additional. 
      e.preventDefault(); 
     } else if (wordCount > max) { 
      var substring = words.slice(0, max).join(' '); 
      $("#text").val(substring + ' '); 
     } 
    });   
}); 
0

雖然你已經接受了答案,我想我也許能提供一個稍微更完善的版本:

function limitWords(max){ 
    // setting the value of the textarea: 
    $(this).val(function(i,v){ 
    // i: the index of the current element in the collection, 
    // v: the current (pre-manipulation) value of the element. 

    // splitting the value by sequences of white-space characters, 
    // turning it into an Array. Slicing that array taking the first 10 elements, 
    // joining these words back together with a single space between them: 
     return v.split(/\s+/).slice(0,10).join(' '); 
    }); 
} 

$('#demo').on('keyup paste input', limitWords); 

JS Fiddle demo

參考文獻: