jquery多组时间以对象数组形式保存

时间:2022-07-25
本文章向大家介绍jquery多组时间以对象数组形式保存,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

需求:

1:点击新增区域的按钮的时候,会新增一行输入框,可以选择输入数据,输入时间

2:输入完成之后,点击保存按钮,将输入的时间以对象数组的格式提交给后端

3:每一组时间是一个对象,每个对象包括开始时间和结束时间,

三组就是三个对象,存放在数组里面。

提交到后端的格式

{"criminalFences":[{"startTime":"09:00","stopTime":"17:00"},{"startTime":"09:00","stopTime":"17:00"},{"startTime":"09:00","stopTime":"17:00"}]}

示例代码

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
	<head>
		<title>保存时间</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
		<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
		<script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
		<style>
		</style>
	</head>
	<body>
		<div id="timeCont"></div>
		
		<button type="button" class="btn blue" id="fatBtn">新增区域</button>
		<button type="button" class="btn blue" id="addBtn">保存</button>
	</body>
	<script type="text/javascript">
		/* 新增检测时间 */
		$("#fatBtn").click(function() {
			
			var htm = "";
			htm += "<div class='form-group'>";
			htm += "<label class='col-sm-3 control-label' >区域监测时间段:</label>";
			htm += "<div class='col-sm-4'>";
			htm += "<input type='text' class='form-control sleepStart1'  name='startTime' value='09:00'  ></input>";
			htm += "</div>";
			htm += "<div class='col-sm-4'>";
			htm +="<input type='text'  class='form-control sleepStop1'   name='stopTime'    value='17:00'></input>";
			
			htm += "</div>";
			htm += "</div>";
			$('#timeCont').append(htm);			
			/* 删除时间 */
			$(".dateDel").on("click", function() {
				$(this).closest('.form-group').remove();
			})
		});
		$("#addBtn").on("click", function() {
			var params = {
				criminalFences: getTimes(),
			}
			alert(JSON.stringify(params))
			$.ajax({
				contentType: 'application/json',
				url: basePath + "/criminal",
				data: JSON.stringify(params),
				type: "post",
				success: function(data) {
				},
				error: function(data) {
					msg(5, "服务器繁忙");
				}
			});

		})
		//获取时间周期
		function getTimes() {
			var times = new Array(); //创建list集合
			$("input[name='startTime']").each(function(i, value) {
				var obj = {};
				obj.startTime = $(this).val();
				times.push(obj);

			});
			$("input[name='stopTime']").each(function(i, value) {
				times[i].stopTime = $(this).val();
			});
			return times;
		}
	</script>
</html>

效果: