[英]Javascript make table with rows and columns given by user and change each cells colour onclick
我有一個代碼,用戶在其中輸入行數和列數。 在給定的行和列的表的創建過程中,每個單元格都有一個onClick事件,用戶單擊任何單元格,單元格的背景顏色就會更改。 在我的代碼中,如何更改單元格的背景顏色?
<body>
Grid Height:
<input id="n1" type="number" name="height" min="1" value="1">
Grid Width:
<input id="n2" type="number" name="width" min="1" value="1">
<input type="submit" onclick="makegrid()">
<table width="100px" height="100px" id="myTable" border="1" style="border-collapse:collapse" >
</table>
<script>
var x,rn,cn;
function makegrid()// function called after submit button is clicked
{
rn = parseInt(document.getElementById("n1").value); //fetches the entered rows by user
cn = parseInt(document.getElementById("n2").value); //fetches the entered column by user
for(var r=0;r<rn;r++)
{
x=document.getElementById("myTable").insertRow(r); //insert row to the table
for(var c=0;c<cn;c++)
{
var y= x.insertCell(c); //insert cells to each row
}
}
}
</script>
將click
偵聽器添加到文檔,檢查clicked元素是否為td
如果是,則更改單元格的背景顏色。
var x, rn, cn; function makegrid() // function called after submit button is clicked { rn = parseInt(document.getElementById("n1").value); //fetches the entered rows by user cn = parseInt(document.getElementById("n2").value); //fetches the entered column by user for (var r = 0; r < rn; r++) { x = document.getElementById("myTable").insertRow(r); //insert row to the table for (var c = 0; c < cn; c++) { var y = x.insertCell(c); //insert cells to each row } } } document.addEventListener('click', ({target}) => { if (target.tagName == "TD") { target.style.backgroundColor = "red"; } });
Grid Height: <input id="n1" type="number" name="height" min="1" value="1"> Grid Width: <input id="n2" type="number" name="width" min="1" value="1"> <input type="submit" onclick="makegrid()"> <table width="100px" height="100px" id="myTable" border="1" style="border-collapse:collapse"> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.