使用jQuery实现修改表格,详细讲解如何实现(完成增删改和复制的操作)

55 阅读1分钟

使用jQuery修改表格(完成增删改和复制的操作)

表格实现的要求

表格模板

  1. 使用jquery选择器和dom操作相关内容,完成这个表格操作,
  2. 增加的行中的内容自订,保证为一格文本,一格数字即可
  3. ==price.toLocaleString('zh',{style:'currency',currency:'CNY'})== 这个代码可以将数字格式化为人民币格式

代码效果演示

增加一行 在这里插入图片描述 在这里插入图片描述 删除第二行 在这里插入图片描述

修改标题样式 在这里插入图片描述

复制最后一行 在这里插入图片描述

CSS样式

<style type="text/css">
	table{
		border-top: 1px solid #000000;
		border-right: 1px solid #000;
		width: 400px;
		text-align: center;
	}
	th{
		border-left: 1px solid #000;
		border-bottom: 1px solid #000;
	}
	td{
		border-left: 1px solid #000;
		border-bottom: 1px solid #000;
	}
</style>

引入jQuery文件

<script src="js/jquery-3.6.0.js" type="text/javascript" charset="utf-8"></script>

HTML

<table cellspacing="0" cellpadding="0" id="table">
	<tr>
		<th>书名</th> <th>价格</th>
	</tr>
	<tr>
		<td>看得见风景的房间</td><td>¥30.00</td>
	</tr>
	<tr>
		<td>60个瞬间</td><td>¥32.00</td>
	</tr>
</table>
<button type="button" class="add">增加一行</button>
<button type="button" class="remove">删除第2行</button>
<button type="button" class="change">修改标题样式</button>
<button type="button" class="cc">复制最后一行</button>

JS

实现实现表格增删改以及复制某一行

$(function(){
	// 添加新的一行
	$(".add").click(function(e){
		// console.info(e);
		var tr = $("<tr class='a'></tr>");
		var book = "<td><input type='text' class='text' id='title'/></td>";
		var num = "<td><input type='text' class='text' id='num'/></td>";
		tr.html(book+num);
		// $("#table").append("<tr>"+book+num+"</tr>");
		$("#table").append(tr);
		tr.slideDown();
		
		// 回车 键盘事件 保存输入在 input 框中的内容
		$(document).keydown(function(e){
			// console.info(e);
			if(e.key=="Enter"){
				// console.info($("#title").val()+$("#num").val());
				// 运用替换节点 将之前的input框 替换掉
				$(".a").replaceWith("<tr>"+"<td>"+$("#title").val()+"</td>"+"<td>"+"¥"+$("#num").val()+"</td>"+"</tr>");
			};
		});
	});
	
	// 删除第二行
	$(".remove").on("click",function(){
		// 索引号 2 remove 删除
		$("tr").eq(2).remove();
	});
	
	// 修改标题样式
	$(".change").click(function(e){
		var book = "<th><input type='text' class='text' id='title1'/></th>";
		var num = "<th><input type='text' class='text' id='num1'/></th>";
		var tr = $("th").parent();
		tr.replaceWith("<tr class='upd ate'>"+book+num+"</tr>");
		$(document).keydown(function(e){
			// console.info(e);
			if(e.key=="Enter"){
				// console.info($("#title").val()+$("#num").val());
				// 运用替换节点 将之前的input框 替换掉
				$(".update").replaceWith("<tr>"+"<th>"+$("#title1").val()+"</th>"+"<th>"+$("#num1").val()+"</th>"+"</tr>");
			};
		});
	})
	
	// 复制最后一行 添加在最后一行
	$(".cc").click(function(){
		$("#table tr:last").clone(true).appendTo($("table tr:eq(0)").parent());
	});
	
	// 鼠标移动 高亮显示
	$("tr").mouseover(function(){
		$(this).css("background-color","#ffb3b3").siblings().css("background-color","");
	});
	// 鼠标离开后高亮显示取消
	$("tr").mouseout(function(){
		$(this).css("background-color","");
	});
})

以上便是本篇博客文章的所有内容 如果该文章对你的学习有所帮助和启发 还请点赞支持一下 谢谢~