---
title: "jquery实现表格行动态增删"
author: "hzp"
date: "2011-04-07T11:19:28Z"
tags: ["jQuery"]
categories: ["Web前端"]
slug: "jquery"
draft: false
lastmod: "2012-09-26T08:42:34Z"
id: 989221
url: "https://hzp.iteye.com/blog/989221"
---

```
<script src="jquery-1.5.1.min.js"></script>

<script>

	$("document").ready(function(){

		var tr;//用于药品显示行保存副本

		//增加药品显示行

		$("input#add").click(function(){

			//当药品行没有全删，则直接复制行，全删时，则用副本复制行

			if(tr==null)

				$("#detail").clone().appendTo($("#mytable"));

			else

				tr.clone().appendTo($("#mytable"));

		});

		//全选中药品显示行

		$(":checkbox#all").click(function(){

			$("input[type=checkbox]").attr("checked",$("input#all").attr("checked"));

		});

		//删除所选药品显示行

		$(":button#btnDel").click(function(){

			tr=$("#detail").clone();//保存第一行副本，防止全删时无法复制行

			$("input:checked[id!=all]").parent().parent().remove();	//除标题行外，删除所有所选行						   

		});

	});

</script>
```

 

 

```
<input type="button" id="add" value="增加药品" />

    <input type="button" id="btnDel" value="删除所选" />

  <br />

  <br />

    	<table width="650" border="0" id="mytable">

        <tr align="center">

    	    <td width="34" align="left"><input type="checkbox" id="all" /></td>

    	    <td width="113" align="center">药名</td>

    	    <td width="75" align="center">规格</td>

    	    <td width="80" align="center">数量</td>

    	    <td width="76" align="center">单价</td>

    	    <td width="83" align="center">生产日期</td>

    	    <td width="74" align="center">生产批次</td>

    	    <td width="81" align="center">失效日期</td>

        </tr>

        <tr id="detail">

        	<td width="34"><input type="checkbox"/></td>

            <td width="113"><input name="medicineName" type="text" size="15"/></td>

            <td width="75"><input name="type" type="text" size="10"/></td>

            <td width="80"><input name="amount" type="text" size="10"/></td>

            <td width="76"><input name="price" type="text" size="10"/></td>

            <td width="83"><input name="productionTime" type="text" size="10"/></td>

            <td width="74"><input name="produtionBatch" type="text" size="8"/></td>

          <td width="81"><input name="expires" type="text" size="10"/></td>

        </tr>

  	  </table>
```