如何使用javascript动态附加卡?

时间:2017-05-26 14:59:59

标签: javascript html dom dynamic

function a()
{ 
   var a1 = "<div class=w3-container><div class=w3-card-4 w3-dark-grey style=width:25%><div class=w3-container w3-center><p>video</p><img src= ";
  var a = [ " https://image.ibb.co/cE0COF/java_mini_logo.jpg ",
       " https://preview.ibb.co/jaNQdF/marguerite_daisy_beautiful_beauty.jpg"];
  var a2= " alt=sir pic style=width:80%><p>John Doe</p></div></div></div>";
  
  var g; 
  for(var i=0;i<2;i++)
    { g= document.createElement('div');
        g.id = i;
     var abc = a1+a[i]+a2;
     document.getElementById(g.id).innerHTML=abc;
     
    }  
}

我试图在循环中输入用户输入卡,即2(这里)首先创建元素然后为其分配ID然后通过为其分配不同的图像URL来添加使其成为卡的代码

1 个答案:

答案 0 :(得分:1)

您忘记了append每个divbody的内容。

您可以使用appendChild方法执行此操作。

function a()
{ 
   var a1 = "<div class=w3-container><div class=w3-card-4 w3-dark-grey style=width:25%><div class=w3-container w3-center><p>video</p><img src= ";
  var a = [ " https://image.ibb.co/cE0COF/java_mini_logo.jpg ",
       " https://preview.ibb.co/jaNQdF/marguerite_daisy_beautiful_beauty.jpg"];
  var a2= " alt=sir pic style=width:80%><p>John Doe</p></div></div></div>";
  
  var g; 
  for(var i=0;i<2;i++)
  { 
      g= document.createElement('div');
      g.id = i;
      document.body.appendChild(g);
      var abc = a1+a[i]+a2;
      document.getElementById(g.id).innerHTML=abc;         
    }  
}
a();