我有一个基于 Web 的程序,它定期从服务器(使用 Node.js 和 socket.io)接收一行文本消息,我将其附加到滚动 DIV。消息是简单的文本;例如,“输入切换失败”。
socket.on('statusMessage', function (newMessage) {
$('#statusMessageDiv').append(newMessage + "<br>");
});
如何在新消息进来时删除旧消息,以便将显示的消息限制为最后 200 条左右?
最佳答案
将消息包装在一个元素中,对元素进行计数,如果超过 200,则移除最后附加的(第一个):
socket.on('statusMessage', function (data) {
$('<p />', {text : newMessage}).appendTo('#statusMessageDiv');
if ( $('p', '#statusMessageDiv').length > 200 )
$('p', '#statusMessageDiv').first().remove();
});
关于javascript - 如何限制定期向其中添加消息的 DIV 中的文本量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16545602/