Add to webpage in javascript

What I want to do is: a web page with constantly updated content. (In my case, it is updated every 2 seconds). New content is added to the old, not rewritten.

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, only one line is printed in IE and Firefox, and the page will no longer be updated. Interestingly, in Chrome, lines are printed continuously, and this is what I am looking for.

I know that document.write () is called when the page loads according to this link . As such, this is definitely not a way to keep the web page up to date. What would be the best way to achieve what I want to do?

Completely new to Javascript. Thanks.

Lily

+4
source share
5 answers

You can add the innerHTML property:

 var number = 0; function send_msg() { document.getElementById('console').innerHTML += (number + " " + msg_list[number%4]+'<br/>'); number = number + 1; } 

This code will add a message to the element with the identifier console , for example

 <div id="console"></div> 

By the way, it is bad practice to call setInterval with a string.

Instead, pass a function like this:

 var my_interval = setInterval(send_msg, 2000); 
+1
source

I would start by looking at the jQuery library. This will save you a lot of pain.

What you want to do is save the inserted rows into the table using, for example:

 $('table tbody').append('<tr><td>some value</td></tr>'); 
+1
source

I would have a div or some other container, for example:

 <div id="msgDiv"></div> 

Then write it using .innerHTML , for example:

 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.getElementById("msgDiv").innerHTML += number + " " + msg_list[number%4]+'<br/>'; number++; } var my_interval = setInterval(send_msg, 2000); 

Here you can see a working example.

+1
source

This will be a great opportunity for you to learn a little DOM programming.

Using the DOM to refresh the page should result in less overhead than just combining more HTML into it. Find the node where you want to put the updates in and add appendChild for each subsequent addition.

+1
source

Answers to this question may be helpful: What is an easy way to web-analyze my command line leader?

0
source

Source: https://habr.com/ru/post/1308295/


All Articles