簡體   English   中英

在keypress上從textarea獲取最后一行

[英]Get last line from a textarea on keypress

我有一個textarea字段,在每個按鍵上,我想將textarea中的最后一行推到一個數組。

目前,我正在每個按鍵上構建數組以獲取textarea中的最后一行。 有沒有辦法優化這個? 意思是,在textarea中獲取最后一行而不必構造數組。

jQuery('#mytextarea').keypress(function() {
    lines = jQuery('#mytextarea').text().split("\n");
    lastLine = lines[lines.length - 1];

});

if(.. some condition ..) {
myArray.push(lastLine);

實際上,有一種方法可以優化它。 優化主要是內存使用 - 實際的CPU使用率也得到了提高。

優化版本依賴於lastIndexOf() 它如下:

jQuery("#mytextarea").keypress(function() {
     var content = this.value;
     var lastLine = content.substr(content.lastIndexOf("\n")+1);
});

您會注意到一些微優化:

  • this已經是DOM元素了。 重新調用jQuery只是為了獲取文本內容。 在處理器上節省一點
  • 使用lastIndexOf允許我最后一次后得到任何東西\\n

DogbertlastIndexOf提供了一個基准: http//jsperf.com/splitting-large-strings

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM