(一)普通版:
// 要求:
// 在页面渲染九九乘法口诀
// 定义变量 用于拼接字符串的
var str = "";
// 外部循环
for(var i = 1 ; i <= 9 ; i ++) {
// 内部循环
for(var j = 1 ; j <= i ; j ++){
// 字符串拼接
// str += i + "*" + j + "=" + ( i * j) + " <br>"//错误的思想 ,每一行都换行了
str += j + "*" + i + "=" + ( i * j) + " "
}
// 拼接换行的标签
str +="<br>";
}
// 渲染字符串
document.write(str);
效果图如下:
(二)优化版:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>javascript 阶段</title>
<style>
table , td {
border:1px solid #fff;
border-collapse: collapse;
}
table tr td {
width: 100px;
height: 50px;
background-color: #ccc;
text-align: center;
line-height: 50px;
font-weight: bold;
}
table tr td:nth-of-type(2n) {
background-color: red;
}
table tr td:nth-of-type(2n-1) {
background-color: green;
}
/* 居中 */
.container {
width: 1200px;
margin: 0 auto;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<!-- <table cellpadding="0" cellspacing="0"> -->
<!--
<table>
<tr>
<td>1 * 1 = 1</td>
</tr>
</table>
-->
<script>
// 定义变量 记录html代码字符串
var str = ""
str +="<table class='container'>"
// 外部循环 (行)
for(var i = 1 ; i <= 9 ; i ++){
// 拼接字符串 tr标签
str += "<tr>"
// 内部循环(列)
for(var j = 1 ; j <= i ; j ++){
// 拼接字符串 td标签
str += "<td>"+j+" * "+i+" = "+( i * j )+"</td>";
}
str += "</tr>"
}
str +="</table> "
// 渲染字符串
document.write(str);
</script>
</body>
</html>
效果图如下:
PS:优化版是添加了样式优化的。