从textarea删除顶行的最新(和快速)方法 [英] Neatest (and fast) way to remove top lines from a textarea
问题描述
我有一个显示最后 1000
日志文件行的网页,然后通过AJAX每次 x
秒加载新内容内容(如果有的话)并附加到textarea与 $('#log')。append(new_data)
,一种 tail -f
。
I have a webpage that displays last 1000
lines of a logfile then updates via AJAX every x
seconds loading new content (if any) and appending to textarea with $('#log').append(new_data)
, a sort of tail -f
.
一段时间后,当附加太多行并且页面变慢或无响应时,问题就会出现。
The problems come up after some time when too many lines are appended and the page becomes slow or unresponsive.
所以我想限制行数,比如5000,这意味着我应该:
So I'd like to limit number of lines to, say, 5000 so it means I should:
- 检索
new_data
- 计算
overflow = 5000 - lines_ in_new_data - lines_in_textarea
- 如果
溢出> 0
从textarea删除第一个溢出
行 - 将new_data附加到textarea
- retrieve
new_data
- calculate
overflow = 5000 - lines_ in_new_data - lines_in_textarea
- if
overflow > 0
remove firstoverflow
lines from textarea - append new_data to textarea
在我看来,这涉及两个<$ c $的一个或多个拆分('\ n')
c> textarea 和 new_data
值然后使用数组长度和切片,但我想如果有更简洁或更好的方法来实现这一点。
In my mind this involves one or more split('\n')
of both textarea
and new_data
values then use array lengths and slicing but I guess if there's a neater or better way to accomplish this.
推荐答案
您应该可以使用单个拆分
然后,如下所示:
You should be able to use a single split
and then join
after truncating the data, something like this:
// on data retrieved
var total = ((textarea.value
? textarea.value + "\n"
: "")
+ new_data).split("\n");
if (total.length > 10)
total = total.slice(total.length - 10);
textarea.value = total.join("\n");
工作示例: http://jsfiddle.net/ArvQ7/ (为简洁起见减少到10行)
Working example: http://jsfiddle.net/ArvQ7/ (cut to 10 lines for brevity)
这篇关于从textarea删除顶行的最新(和快速)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!