jS生成表格

332 阅读1分钟
	//单元格样式
	<style type="text/css">
		*{
			margin: 0;
			padding: 0;
		}
		.tb{
			text-align: center;
			font-weight: bold;
			font-size: 30px;
			border-collapse: collapse;				
		}
		.tb td{
			border: cadetblue 1px solid;
			width:120px;
			height: 120px;
		}
	</style>
</head>
<body>
	<script type="text/javascript">
		
		let table = document.createElement('table')
		table.classList.add('tb')
		//表格的行循环
		for (let i = 0; i < 5; i++) {
			let tr = document.createElement("tr")
			table.appendChild(tr)
			//表格的列循环
			for(let j = 0; j < 5; j++){
				let td = document.createElement('td')	
				td.innerHTML = i + '-' + j
				td.onclick = function(){
					alert(this.innerHTML)
				}
				tr.appendChild(td)
			}
			//点击删除整行
			let td = document.createElement('td')
			td.innerHTML = '删除'
			td.onclick = function(){
				let needDel = confirm('确定删除?')
				if (needDel)
				td.parentElement.remove()
			}
			tr.appendChild(td)
		}
		document.body.appendChild(table)
		
		
		let mytd = table.children[1].children[2]
		mytd.style.color = 'red'
		//设置单元格的样式
		//选中表格第一个单元格进行css设置
		table.firstElementChild.firstElementChild.style.color='green'
		//选中表格第一个单元格的下一个单元格进行css设置
		table.firstElementChild.firstElementChild.nextElementSibling.style.color='pink'
		//选中表格最后一个单元格进行css设置
		table.lastElementChild.lastElementChild.style.color='skyblue'
		//选中表格最后一个单元格的前一个单元格进行css设置
		table.lastElementChild.lastElementChild.previousElementSibling.style.color='orange'		
	</script>