如何使用循环获取此dom树?

时间:2018-02-11 09:29:24

标签: javascript jquery html html5

我想创建一个像这样的HTML代码:

<div class='parent'>
    <div class="firstChild"></div>
    <div class="secondChild"></div>
</div>
<div class='parent'>
    <div class='firstChild'></div>
    <div class="secondChild"></div>
</div>
<div class='parent'>
    <div class='firstChild'></div>
    <div class="secondChild"></div>
</div>

使用:

  var content = '';
    for(var i = 0 ; i < 4 ; i++){
        content += '<div class="parent">';
            content += '<div class="firstChild"></div>';
            content += '<div class="secondChild"></div>';
        content += '</div>';
    }
    $('.conainer').html(content);

但是我得到了一些其他的东西:

<div class='parent'>
    <div class='firstChild'></div>
    <div class="secondChild">
        <div class='parent'>
        <div class='firstChild'></div>
        <div class="secondChild"></div>
   </div>
</div>

如何修复此问题并获得正确的dom树?

3 个答案:

答案 0 :(得分:0)

似乎你的单引号放错了地方,

尝试使用一些双引号,以避免破坏字符串

参见示例:

&#13;
&#13;
var content = '';
    for(var i = 0 ; i < 4 ; i++){
        content += '<div class="parent">';
            content += '<div class="firstChild"></div>';
            content += '<div class="secondChild"></div>';
        content += '</div>';
    }
console.log(content);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

对于Simplicity,您也可以这样尝试

how to make a call from outside of an actor as fast as inside it does?

答案 2 :(得分:0)

&#13;
&#13;
$(function(){
      var content = '';

      for(var i = 0 ; i < 4 ; i++){
        content += "<div class='parent'>Parent";
          content += "<div class='firstChild'>firstChild</div>";
          content += "<div class='secondChild'>secondChild</div>";
        content += "</div>";
      }
      $('.conainer').html(content);
});
&#13;
.parent {
background: red;
}
.firstChild {
background: green;
}
.secondChild {
background: blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="conainer"></div>
&#13;
&#13;
&#13; 使用&#34;&#34; s作为字符串文字,并使用&#39; &#39;逃避。