Home >Web Front-end >JS Tutorial >jQuery implements dynamically adding and deleting a div_jquery

jQuery implements dynamically adding and deleting a div_jquery

WBOY
WBOYOriginal
2016-05-16 15:45:351430browse

This article mainly gives you a brief introduction on how to dynamically add and delete a div in an element, hoping to get the effect of drawing inferences from one example.

The code example is as follows:

<!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>脚本之家欢迎您</div>");
})
</script>
</head>
<body>
<div id="father"></div>
</body>
</html>

The above code can add a div to the parent div. Next, we will introduce how to delete a div. Only the core code is given below:

$(document).ready(function(){
 $("#father").prepend("<div>脚本之家欢迎您</div>");
 $("div").remove("#father div");
})

The above code can remove the added div.

Example 2:

<!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>

Related reading:

1. For the prepend() function, please refer to jQuery’s prepend() method chapter.

2. For the remove() function, please refer to jQuery’s remove() method chapter.

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