简体   繁体   中英

How can I dynamically add new content to my page each time my array length increases?

I have a function that is adding new strings to an array at random intervals. How can I display with javascript and/or jquery each new string on my page every time the length of the array increases?

You can set a recursive timer function that will updated your array display container every time it is called (adapted from Javascript dynamic array of strings ):

<html>
    <body>
        <script type="text/javascript">
            var arr = [];
            function add() {
              arr.push("String " + Math.random());
            }
            function show() {
              var html = '';
              for (var i = 0; i < arr.length; i++) {
                html += '<div>' + arr[i] + '</div>';
              }
              var con = document.getElementById('container');
              con.innerHTML = html;
            }
            function start() {
              setTimeout(function() {
                add();
                // Note: you can call show in an independent timeout
                show();
                start();
              }, 1000);
            }
        </script>

        <input type="button" onclick="start();" value="start" />
        <br />
        <div id="container"></div>
    </body>
</html>

Or you can make it smarter and update the container only if the array's length changed.

Yet another way is to pass a display container update callback to your array update function, so that whenever you update your array - you just go and re-display your array.

<html>
    <body>
        <script type="text/javascript">
            var arr = [];
            var lastDisplayed = 0;

            function add() {
              arr.push("String #" + lastDisplayed + ": " + Math.random());
              show(); // Update display container
            };
            function show() {
              var node;
              var textnode;
              var container = document.getElementById('container'); // Get parent container
              for (; lastDisplayed < arr.length; lastDisplayed++) {
                node = document.createElement("li"); // Create a <li> node
                textnode = document.createTextNode(arr[lastDisplayed]); // Create a text node
                node.appendChild(textnode);        
                container.appendChild(node);
              }
            };
            function start() {
              setTimeout(function() {
                add();
                start();
              }, 1000);
            };
        </script>

        <input type="button" onclick="start();" value="start" />
        <br />
        <ul id="container"></ul>
    </body>
</html>

Internally, Angular and other frameworks implement a combination of these approaches.

Important note: depending on your application, you might want to explore different approaches to updating your page to preserve responsiveness and performance of your interface. For example, you might want to space your GUI updates in time if array elements are added too often. You may also want to keep adding elements to your DOM model (see the second example) instead of rewriting it (like in the first example) if the existing elements of your array remain unchanged. Similar issues might need to be considered if using a dedicated framework like Angular.

I would recommend using a library that handle property subscriptions like knockout or angular, but since that wasnt mentioned in the question I will give this example.

var someArray = [];
var standardPush = someArray.push;
someArray.push = function(){
    // depending on your requirements you can switch these next two lines around
     for (var i = 0; i < arguments.length; i++) {
       updateUI(arguments[i]); // call code to update UI
       standardPush(arguments[i]); // actually ad record to array   
    }
}
function updateUI(record){
  // Some code that updates your UI
  // example
  $("#container").append($("<div>").text(record));
}

then just call it like a normal array.push

someArray.push(someRecord);    
// or
someArray(record1, record2, record3....);

This code is more fun than practical, I again would recommend a library that handles property subscriptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM