1. 程式人生 > >ES6 使用字串模板生成HTML、及擴充套件運算子[...]的使用

ES6 使用字串模板生成HTML、及擴充套件運算子[...]的使用



<html>

<head>
<title>ES6</title>
<style>
input.active{
   background:red;
}
#first > div {
    width:200px;
	height:200px;
	background:#ccc;
	display:none;
}
#first > div:first-of-type{
   display:block;
}
</style>
</head>

<body> 
<script>
    const $=obj=>[...document.querySelectorAll(obj)];
	let json = {
	  "input" : ["1","2","3"],
	  "content" : ["第一介面","第二介面","第三介面"]
	};
	//模板生成
	let node = data =>`<div id=first>
	${data.input.map((i)=>`<input type=button value=${i}>`).join('')}
	${data.content.map((i)=>`<div>${i}</div>`).join('')}
	</div>`;
	document.body.innerHTML= node(json);
	let allInput = new Set($('input'));
	[...allInput][0].className = 'active';
	let allDiv = new Set($('#first > div'));
	[...allInput].forEach((v,i)=>{
	   v['onclick'] = ()=>{
		  [...allInput].forEach((v)=>{v.className=''});
		  [...allInput][i].className='active';
	      [...allDiv].forEach((v)=>{v.style.display='none';});
		  [...allDiv][i].style.display='block';
		  
	   }
	});
	
</script>
</body>

</html>