在使用JavaScript实现更多负载时遇到问题。谁能帮忙吗?
我尝试使用for循环。因为我是JavaScript的初学者,所以能够实现一些功能。
<script>
let ar = ['a', 21, 'b'];
let postToShow = 1;
function load(val) {
for (let i = 0; i < ar.length; i++) {
if (postToShow % (ar.length + 1) !== 0) {
document.getElementById('num').innerHTML += ar[postToShow - 1] + "<br />";
postToShow++;
return;
}
}
}
</script>
<body>
<button onclick="load()" id="loadMore">Load more </button>
</body>
我希望根据postToShow
加载输出。请帮助...
答案 0 :(得分:0)
在这里for循环并不是一个理想的解决方案,因为您要一个接一个地添加内容。无需每次都遍历内容。
一种更简单的解决方案是跟踪某种计数器,并以此方式从数组中获取内容。
您可以尝试这样的事情
<ul id="content-wrapper"></ul>
<button onclick="load()" id="loadMore">Load more </button>
const content = ['a', 'b', 'c', 'd', 'e', 'f'];
let counter = 0;
function load() {
var node = document.createElement("li"); // Create a <li> node
var textnode;
if(content[counter]) {
// Create a text node if there is text
textnode = document.createTextNode(content[counter]);
} else {
// Return a message if there is no more
textnode = document.createTextNode('No Data');
}
counter++; // Increment counter
node.appendChild(textnode); // Append the text to <li>
document.querySelector('#content-wrapper').appendChild(node)
}
Codepen here。
如果您需要进一步的帮助,请告诉我。