我在使用 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
加载。请帮忙...
鉴于您要逐个添加内容,因此 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)
}
代码笔在这里。
如果您需要任何进一步的帮助,请告诉我。