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>


猜你喜欢

转载自blog.csdn.net/xcc_2269861428/article/details/80842488