日期:2014-05-16  浏览次数:20807 次

求一小段 JS
当消息超过10行,自动清除最早的消息(局部清除,不重写整个body)。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<div id="chat">
<div id="msg"></div>
</div>
<input type="button" onclick="insertMsg();" value="New Message"/>
<script type="text/javascript">
var i = 1;
function insertMsg()
{
var chat = document.getElementById("chat");
var msg = document.getElementById("msg");
var div = document.createElement("div");
chat.name = "box";
div.innerHTML = "新消息" + i;
chat.insertBefore(div,msg.nextSibling);
i++;
}
</script>
</body>
</html>

------解决方案--------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<div id="chat">
<div id="msg"></div>
</div>
<input type="button" onclick="insertMsg();" value="New Message"/>
<script type="text/javascript">
var i = 1;
function insertMsg()
{
var chat = document.getElementById("chat");
var msg = document.getElementById("msg");
var div = document.createElement("div");
chat.name = "box";
div.innerHTML = "新消息" + i;
chat.insertBefore(div,msg.nextSibling);
i++;

var div = chat.childNodes;
var n = div.length;
if(n > 12)
{
for(var j = 12; j < n; j++)
{
chat.removeChild(div[j]);
}
}
}
</script>
</body>
</html>