gpt4 book ai didi

javascript - 使用javascript循环div

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:28 26 4
gpt4 key购买 nike

我试图循环遍历 div 并动态插入 div 项目,但它只是将一个 div 项目插入到 html 页面中。这是我的代码:

     function loadArticles ()      {        
var request = new XMLHttpRequest();
request.onreadystatechange = function (){
if (request.readyState === XMLHttpRequest.DONE){
var articles = document.getElementById('articles');
if (request.status === 200) {
var articleData = JSON.parse(this.responseText);
for (var i=0; i< articleData.length; i++) {
var content = `<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="post-preview">
<a href="/${articleData[i].title}">
<h2 class="post-title">
${articleData[i].heading}</h2>
<h3 class="post-subtitle">
${articleData[i].subtitle}</h3>
</a>
<p class="post-meta">Posted by <a href="#">${articleData[i].author}</a> on Date ${articleData.date[i].toDateString()}</p>
</div>
</div>
</div>
</div>`;
}
articles.innerHTML = content;
} else {
articles.innerHTML('Oops! Could not load all articles!')
}
}
};

最佳答案

InnerHtml 是一个字符串。所以你的代码将覆盖内容i次。您需要添加到字符串:

articles.innerHTML+=content;

这一行需要位于 for 循环内部...

关于javascript - 使用javascript循环div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40693076/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com