jQurey动态添加/删除DIV(原创自Zjmainstay)

本文介绍如何利用jQuery实现动态添加与删除DOM元素的功能。通过一个简单的示例,展示了当用户点击按钮时如何向页面中添加新的div,并提供删除已添加元素的方法。此过程涉及对jQuery的选择器和事件处理的理解。

canrun

<html>
<head>
<script type="text/javascript" src="http://files.cnblogs.com/Zjmainstay/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
var num = 1;
$(document).ready(function(){
    $("#add").click(function(){
        $("#new").append('<div id="new_sub'+num+'" class="sub"><span>new_sub'+num+'&nbsp;&nbsp;</span><span class="del">&nbsp;X&nbsp;</span></div>');
        $(".del").click(function(){
            $(this).parent().remove();
        });
        num++;
    });
});
</script>
<style type="text/css">
#add {background:#abc;width:15%;text-align:center;cursor:pointer;}
.new_sub_c{background:#dde;}
.del {color:red;border:1px solid yellow;float: right;cursor:pointer;}
.sub {border: 1px solid #AABBCC;height: 90px;width: 150px;}
</style>
</head>
<body>
    <div id="add"><u>Click to Add a DIV</u></div>
    <div id="new"></div>
</body>
</html>

<!-- 摘要效果 -->
<!--
<div id="add" onclick='var num=!$("#new").val()|$("#new").val()
    $("#new").append("<div class=\"sub\"><span>new_sub"+num+"</span><span class=\"del\">X</span></div>")
    $(".del").click(function(){
        $(this).parent().remove()
    });num++;$("#new").val(num)'>Click it</div>
<div id="new"></div>
<style>.sub{border:1px solid #abc;width:29.2%;height:90px}.del{padding:0 4px;text-indent:0;color:red;float:right;background:#EBEBEB}#add{background:#abc;width:29.5%;text-align:center;text-indent:0}</style>
-->

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值