动态在javascript中创建元素 [英] Create elements in javascript dynamically

查看:61
本文介绍了动态在javascript中创建元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何在javascript中动态创建一个像这样的元素,因为我想在它获取数据库中的内容时对其进行循环.

How can i create an element like this in javascript dynamically because i want to loop it while it is fetching content in the database.

<div class="card">
<div class="card-image waves-effect waves-block waves-light">
  <img class="activator" src="images/office.jpg">
</div>
<div class="card-content">
  <span class="card-title activator grey-text text-darken-4">Card Title<i class="material-icons right">more_vert</i></span>
  <p><a href="#">This is a link</a></p>
</div>
<div class="card-reveal">
  <span class="card-title grey-text text-darken-4">Card Title<i class="material-icons right">close</i></span>
  <p>Here is some more information about this product that is only revealed once clicked on.</p>
</div>

外观如下: http://materializecss.com/cards.html#reveal

我尝试在Internet上搜索,但我发现只有孩子才能动态创建一个元素.请帮我这是我的机器项目,我们的教授甚至都没有考虑过javascript,我正在盲目地研究它.我设法创建了一些JavaScript,例如函数.抱歉,我的帖子很长.

I have tried searching in the internet and i only found creating one element dynamically with child. Please do help me this is my machine project and our professor doesn't even thought javascript and i am blindly studying this. I have managed to create some of the javascript such as functions. Iam sorry for the long post.

推荐答案

使用jQuery:

仅出于简化目的:

 <div class="card">
   <div class="card-image waves-effect waves-block waves-light">
    <img class="activator" src="images/office.jpg">
   </div>
   <p>other</p>
 </div>

尝试

 $('<div>').class('card').append(
   $('<div>').class('card-image waves-effect').append(
     $('<img>').class('activator').src('images/office.jpg'),
     $('<p>').text(other)
   )
 );

或使用纯Javascript尝试:

or with pure Javascript try:

var div=document.createElement('div');
div.className='card';
var div2=document.createElement('div');
div.appendChild(div2);
etc...

这篇关于动态在javascript中创建元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆