表格添加內容並進行刪除案例
阿新 • • 發佈:2018-02-24
void style char script line pos ack 註冊事件 href
表格都很常見,一般都是用table來寫的,今天我就寫一個dl和dd布局的表格,並往表格裏添加內容,同時點擊刪除按鈕也可以刪掉表格內容。來看代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> *{ margin:0; padding:0;} dl{list-style: none;} .box{ width:400px; height:40px; margin:0 auto;} .box dl{ list-style:none;overflow: hidden;border:1px solid #e5e5e5;} .box dl dt{background: #ff7e7e;font-size:16px;color:#fff;} .box dl dt,.box dl dd{border-bottom:1px solid #e5e5e5;} .box dl dd:last-child{border:none;} .box dl dd a{background:#1E9FFF;color:#fff;padding:5px 10px;font-size: 12px;margin-left:20px;text-decoration: none;} input{margin:10px 20px 10px 0;padding:5px 10px;border:none;outline:0;background:#1E9FFF;color:#fff;} span{padding:10px 20px;display:inline-block;width:60px;text-align: center} </style> <body> <div class="box"> <input id="btnClear" type="button" value="清空內容"/> <input id="btnAdd" type="button" value="添加"/> <dl> <dt> <span>標題</span> <span>標題1</span> <span>標題2</span> </dt> <dd> <span>內容</span> <span>內容</span> <span>內容</span> <a class="btndelte" href="javascript:void(0)">刪除</a> </dd> <dd> <span>內容</span> <span>內容</span> <span>內容</span> <a class="btndelte" href="javascript:void(0)">刪除</a> </dd> <dd> <span>內容</span> <span>內容</span> <span>內容</span> <a class="btndelte" href="javascript:void(0)">刪除</a> </dd> <dd> <span>內容</span> <span>內容</span> <span>內容</span> <a class="btndelte" href="javascript:void(0)">刪除</a> </dd> </dl> </div> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ $("#btnClear").on("click",function(){ $("dl dd").empty(); }); $("#btnAdd").on("click",function(){ $(‘<dd> <span>內容1</span> <span>內容1</span> <span>內容1</span> <a class="btndelte" href="javascript:void(0)">刪除</a> </dd>‘).appendTo("dl")}) $("dl").on("click",".btndelte",function(){ console.log($(this).parent()); $(this).parent().empty(); }) }) </script> </body> </html>
這個案例主要用到的就是on綁定事件,以及appendTo事件。on綁定事件經常會用到,可以委托綁定(寫選擇器就是委托事件),否則就是自己綁定註冊事件。
表格添加內容並進行刪除案例