在按键上从文本区域获取最后一行 [英] Get last line from a textarea on keypress
本文介绍了在按键上从文本区域获取最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个textarea字段,每次按键时,我想将textarea中的最后一行推到一个数组中.
I have a textarea field and on every keypress, I would like to push the last line in the textarea to an array.
当前,我在每次按键时都构造一个数组,以获取文本区域的最后一行.有没有一种方法可以对此进行优化?意思是,无需构造数组即可获得文本区域的最后一行.
Currently, I am constructing the array on every keypress to get the last line in the textarea. Is there a way to optimize this? Meaning, get last line in the textarea without having to construct an array.
jQuery('#mytextarea').keypress(function() {
lines = jQuery('#mytextarea').text().split("\n");
lastLine = lines[lines.length - 1];
});
if(.. some condition ..) {
myArray.push(lastLine);
推荐答案
实际上,有一种方法可以对此进行优化.优化主要是内存使用-实际CPU使用也得到了改善.
Indeed, there is a way to optimize this. The optimization is mostly memory usage - the actual CPU usage is also improved.
优化版本依赖于lastIndexOf()
.如下:
The optimized version relies on lastIndexOf()
. It is as follows:
jQuery("#mytextarea").keypress(function() {
var content = this.value;
var lastLine = content.substr(content.lastIndexOf("\n")+1);
});
您会注意到一些微观优化:
You will notice a couple of micro-optimizations:
-
this
已经是DOM元素.重新调用jQuery只是为了获取文本内容没有什么意义.在处理器上节省一点时间 - 使用
lastIndexOf
可使我在最后一个\n
之后得到任何东西
this
already is the DOM element. There is little point in re-invoking jQuery just to get the text content. Saves a bit on processor- using
lastIndexOf
allows me to get anything after the last\n