使用javascript循环div

时间:2016-11-19 12:47:54

标签: javascript

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

{{1}}

3 个答案:

答案 0 :(得分:1)

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

articles.innerHTML+=content;

这一行需要在for循环中...

答案 1 :(得分:0)

通过在循环内声明内容,您将在每个循环步骤中覆盖内容。你应该在循环之外声明content然后在循环后分配它。

var content = '';

for (var i=0; i< articleData.length; i++) {  
  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;

答案 2 :(得分:0)

尝试这样:

        }
            articles.innerHTML += content;
        } else {
            articles.innerHTML ='Oops! Could not load all articles!';
        }  

你首先要写的是现有的数据。所以使用+。它会附加数据

第二个是syntax error innerHTML=,而不是innerHTML()

   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!';
        }
    }
};