我有一个函数,它以随机的间隔向数组添加新字符串。每次数组的长度增加时,如何用javascript和/或jquery显示我页面上的每个新字符串?
答案 0 :(得分:1)
你可以设置一个递归计时器函数,每次调用它时都会更新你的数组显示容器(改编自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>
或者你可以使它变得更聪明,只有在数组长度发生变化时才更新容器。
另一种方法是将显示容器更新回调传递给您的阵列更新功能,这样每当您更新阵列时 - 您只需重新显示阵列即可。
<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>
在内部,Angular和其他框架实现了这些方法的组合。
重要说明:根据您的应用程序,您可能希望探索更新页面的不同方法,以保持界面的响应性和性能。例如,如果过于频繁地添加数组元素,您可能希望及时分隔GUI更新。如果数组的现有元素保持不变,您可能还希望继续向DOM模型添加元素(请参阅第二个示例),而不是重写它(如第一个示例中所示)。如果使用像Angular这样的专用框架,可能需要考虑类似的问题。
答案 1 :(得分:0)
我建议使用一个处理属性订阅的库,比如knockout或angular,但是因为问题中没有提到我会给出这个例子。
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));
}
然后只需将其称为普通的array.push
someArray.push(someRecord);
// or
someArray(record1, record2, record3....);
这段代码比实际更有趣,我再次推荐一个处理属性订阅的库。