JQurey 添加和删除元素

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
</head>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<style>
.baseDiv {
height : 1%;
width : 100%;
background-color : aqua;
}
.newDiv {
height : 1%;
width : 100%;
background-color : yellow;
margin-top : 1%;
cursor : pointer;
}
</style>


<body>
<button id="addDiv">添加div元素到baseDiv</button>


<div id="baseDiv" class="baseDiv">
<p>这里一个名为baseDiv的div</p>
<p>这是一个段落。</p>

</div>
<br>
<button id="removebaseDiv"  >移除baseDiv</button>
<script>
var num = 1;
$(function(){
    $('#addDiv').bind('click', function(event) {
        $("<div id='div"+ num +"' onclick='removeDiv(this)' class='newDiv'>这是新增的div"+ num +",点击可以删除</div>").appendTo("#baseDiv");
		num++;
    });
})
$(function(){
    $('#removebaseDiv').bind('click', function(event) {
        $('#baseDiv').remove();
    });
})
function removeDiv(node) {
	$('#'+node.id+'').remove();
}
</script>
</body>
</html>

效果图

点击添加div元素到baseDiv 按钮

再次点击添加div元素到baseDiv 按钮

点击这是新增的div1,点击可以删除

点击移除baseDiv 按钮

原文地址:https://www.cnblogs.com/lick468/p/10788706.html