Home  >  Article  >  Web Front-end  >  jQuery实现动态添加和删除一个div_html/css_WEB-ITnose

jQuery实现动态添加和删除一个div_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:37:481186browse

 

本文主要给大家简单介绍一下如何动态的在一个元素添加和删除div,希望能够得到举一反三之效。

代码实例如下:

<!DOCTYPE html><html><head><meta charset="utf-8"><style type="text/css">#father{ width:150px; height:150px; background-color:red;}#father div{ width:50px; height:50px; background-color:green; font-size:12px;}</style><script type="text/javascript" src="/jQuery/jquery-1.8.3.js"></script><script type="text/javascript">$(document).ready(function(){ $("#father").prepend("<div>100素材网</div>");})</script></head><body><div id="father"></div></body></html>

  

以上代码可以在父div中添加一个div,下面再介绍一下如何删除一个div,下面只给出核心代码:

$(document).ready(function(){ $("#father").prepend("<div>100素材网</div>"); $("div").remove("#father div");})

  

以上代码可以移除添加的div。

示例二:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Add And Close Div</title> <script type="text/javascript教程" > $(document).ready(function(){     bindListener();})function addimg(){     $("#mdiv").append('<div class="iptdiv" ><input type="file" name="img[]" class="ipt" /><a href="#" name="rmlink">X</a></div>');          // 为新元素节点添加事件侦听器    bindListener();}// 用来绑定事件(使用unbind避免重复绑定)function bindListener(){    $("a[name=rmlink]").unbind().click(function(){        $(this).parent().remove();     })}</script>  </head>  <body> <form action="" method="post" enctype="multipart/form-data">  <label>请选择上传的图片</label>   <a href="javascript:addimg()" id="addImg">增加图片</a>   <div class="mdiv" id="mdiv">     <div class="iptdiv" ><input type="file" name="img[]" class="ipt" /><a href="#" name="rmlink">X</a></div>    </div>   <input type="submit" name="submit" value="上传图片" /> 

 

 </form>  </body>  </html>

  

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn