로메오의 블로그

jQuery Template Tag 사용하기 본문

App & OS/ETC

jQuery Template Tag 사용하기

romeoh 2022. 1. 24. 11:23
반응형

 

<!DOCTYPE html>

<html lang="ko">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title></title>
	<script src="https://code.jquery.com/jquery-latest.min.js"></script>
	<script src="https://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>

	<template id="template-company">
	    <tr>
	        <td name>{{name}}</td>
	        <td><input type="text" value="{{product}}" product /></td>
	    </tr>
	</template>
</head>
<body>
	<table border="1">
	    <caption>Company</caption>
	    <thead>
	        <tr>
	            <th>이름</th>
	            <th>상품</th>
	        </tr>
	    </thead>
	    <tbody id="container-list"></tbody>
	</table> 
	<button id="btnAdd">추가</button>
	<button id="btnView">확인</button>

	<script type="text/javascript">
		var data = [
			{name:'구글', product:'search', nation: 'USA'}, 
			{name:'삼성', product:'mobile', nation: 'Korea'},
			{name:'애플', product:'pc', nation: 'USA'},
			{name:'소니', product:'game', nation: 'Japan'}
		];
		
		var template = $.trim($('#template-company').html())
		var container = $('#container-list')

		function renderTemplate(obj) {
			var x = template;
			for (var i in obj) {
				var pattern = new RegExp('\\{\\{' + i + '\\}\\}', 'g')
				x = x.replace(pattern, obj[i])
			}
			container.append(x)
		}

		// 초기화 bind
		$.each(data, function(index, obj) {
			renderTemplate(obj)
		})

		// 추가
		$('#btnAdd').on('click', function() {
			var newData = {name:'화웨이', product:'network', nation: 'China'}
			renderTemplate(newData)
		})

		// 데이터 확인
		$('#btnView').on('click', function() {
			var updateData = []
			$('#container-list tr').each(function(index, tr) {
				updateData.push({
					name: $(tr).find('[name]').text(),
					product: $(tr).find('[product]').val()
				})
			})
			console.log(updateData)
		})
	</script>

</body>
</html>
반응형
Comments