简体   繁体   English

每当数组长度增加时,如何动态地向页面添加新内容?

[英]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? 每当数组长度增加时,如何使用javascript和/或jquery在页面上显示每个新字符串?

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 ): 您可以设置一个递归计时器函数,该函数将在每次调用数组显示容器时对其进行更新(改编自Javascript动态字符串数组 ):

<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. 在内部,Angular和其他框架实现了这些方法的组合。

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. 例如,如果阵列元素添加得太频繁,您可能希望及时安排您的GUI更新空间。 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. 如果数组的现有元素保持不变,则可能还需要继续向DOM模型中添加元素(请参见第二个示例),而不是重写它(如第一个示例中一样)。 Similar issues might need to be considered if using a dedicated framework like Angular. 如果使用像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. 这段代码比实际的有趣,我再次推荐一个处理属性订阅的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 每次执行 function 时,如何将数组另存为新的 object 而不会覆盖我的旧数组 - how can you make an array save as a new object each time a function is executed and not overwrite my old array 如何向我的页面动态添加新的输入字段 - How to dynamically add new input fields to my page 如何为每个循环将我的JavaScript添加到我的php中? - How can I add my javascript to my php for each loop? 我如何在body标签之后动态添加div到页面? - how can i dynamically add a div to my page after the body tag? 如何将数据从数组动态添加到表单元格? - How can I add data from my array to the table cells dynamically? 如何在jspdf中将div内容添加到新页面? - How can I add div content to a new page in jspdf? 如何使阵列每次运行都能选择不同的选择? - How can I make my array choose different choices each time it runs? 我会在我的html页面中将onmouseover和onmouseout属性动态地添加到每个锚点,但是它不起作用 - I would dynamically add the onmouseover and onmouseout attributes to each anchor in my html page but it does not work 如何动态更改页面的og:title - How can I dynamically change the og:title of my page 我如何添加自己的 <divs> 动态地添加到容器中? - How can I add my own <divs> to a container dynamically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM