在 javascript 中附加到网页
我想做的是:一个内容不断更新的网页。 (在我的例子中,每 2 秒更新一次)新内容将附加到旧内容而不是覆盖。
这是我的代码:
var msg_list = new Array(
"<message>Hello, Clare</message>", "<message>Hello,Lily</message>",
"<message>Hello, Kevin</message>", "<message>Hello, Bill</message>"
);
var number = 0;
function send_msg()
{
document.write(number + " " + msg_list[number%4]+'<br/>');
number = number + 1;
}
var my_interval = setInterval('send_msg()', 2000);
但是,在 IE 和 Firefox 中,只打印出一行,并且页面将不再更新。有趣的是,在 Chrome 中,这些行被连续打印出来,这正是我正在寻找的。
我知道根据 此链接。所以绝对不是持续更新网页的方式。实现我想做的事情的最佳方法是什么?
完全是Javascript新手。谢谢。
百合
What I want to do is that: a webpage with continuously updating content. (In my case is updating every 2s) New content is appended to the old one instead of overwriting.
Here is the code I have:
var msg_list = new Array(
"<message>Hello, Clare</message>", "<message>Hello,Lily</message>",
"<message>Hello, Kevin</message>", "<message>Hello, Bill</message>"
);
var number = 0;
function send_msg()
{
document.write(number + " " + msg_list[number%4]+'<br/>');
number = number + 1;
}
var my_interval = setInterval('send_msg()', 2000);
However, in both IE and Firefox, only one line is printed out, and the page will not be updated anymore. Interestingly in Chrome, the lines are being printed out continuously, which is what I am looking for.
I know that document.write() is called when the page is loaded according to this link. So it's definitely not the way to update the webpage continuously. What will be the best way to achieve what I want to do?
Totally newbie in Javascript. Thank you.
Lily
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会有一个 div 或其他一些容器,如下所示:
然后像使用
.innerHTML
,如下所示:您可以在此处查看一个工作示例
I would have a div or some other container, like this:
Then write to it like using
.innerHTML
, like this:You can see a working example of this here
您可以附加到
innerHTML
属性:此代码会将消息附加到 id 为
console
的元素,例如By the way, it is bad Practice to call < code>setInterval 带有字符串。
相反,传递函数本身,如下所示:
You can append to the
innerHTML
property:This code will append the message to an element with an id of
console
, such asBy the way, it is bad practice to call
setInterval
with a string.Instead, pass the function itself, like this:
我将从查看 jQuery 库开始。这将为您减轻很多痛苦。
您想要做的是将插入的行保留到表中,使用例如:
I would start by looking at the jQuery library. This will save you a lot of pain.
What you want to do is keep inserted lines into a table, using eg:
这对您来说是学习一点 DOM 编程的绝佳机会。
使用 DOM 更新页面应该会比简单地将更多 HTML 连接到页面中产生更少的开销。找到您想要将更新放入的节点,并对每个后续添加执行appendChild。
This would be an excellent opportunity for you to learn a little DOM programming.
Using the DOM to update the page should result in less overhead than simply concatenating more HTML into it. Find the node you want to put the updates into, and do an appendChild on each subsequent addition.
此问题的答案可能会有所帮助:什么是将我的命令行守护进程网络化的简单方法?
The answers to this question may be helpful: What's a simple way to web-ify my command-line daemon?