javascript生成指定行列table表格程式碼例項

antzone發表於2017-04-13

分享一段程式碼例項,它實現了動態生成指定行列的table表格效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
var lie = 0;
var hang = 0;
function makeTabble() {
  var lie = 0;
  var hang = 0;
 
  hang = document.getElementById('inputOne').value;
  lie = document.getElementById('inputTwo').value;
  document.getElementById('inputOne').value = '';
  document.getElementById('inputTwo').value = '';
  var theTable = document.createElement("table");
  theTable.style.border = "1px solid #8c8c8c"
  for (i = 0; i < hang; i++) {
    var hangEle = document.createElement("tr");
    for (j = 0; j < lie; j++) {
      var lieEle = document.createElement("td");
      lieEle.style.width = "80px";
      lieEle.style.height = "30px";
      lieEle.style.border = "1px solid #8c8c8c"
      hangEle.appendChild(lieEle);
    }
    theTable.appendChild(hangEle);
  }
  document.body.appendChild(theTable);
}
window.onload = function () {
  var obt = document.getElementById("bt");
  obt.onclick = function () {
    makeTabble();
  }
}
</script>
</head>
<body>
<h1>生成表格</h1>
行數:<input type="text" id="inputOne" /> 
列數:<input type="text" id="inputTwo" /> 
<input type="button" id="bt" value="檢視效果"/>
</body>
</html>

程式碼確實非常簡單,更多內容可以參閱相關閱讀。

相關閱讀:

(1).document.createElement()可以參閱document.createElement()一章節。

(2).appendChild()可以參閱appendChild()一章節。

相關文章