我有一个简单的问题要问你。我在这里有一些代码,允许用户在表中告诉他们想要多少行和列。我已经弄清楚了。我无法弄清楚如何添加向上,向下,向左和向右按钮,以便他们可以选择表格中的某个单元格。这就是我需要的样子:
这是我到目前为止的代码:
使用Javascript:
function createTable()
{
var num_rows = document.getElementById('rows').value;
var num_columns = document.getElementById('columns').value;
var theader = '<table border="1">\n';
var tbody = '';
for( var i=0; i<num_rows;i++)
{
tbody += '<tr>';
for( var j=0; j<num_columns;j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
HTML:
<form name="tablegen">
<label># of Rows: <input type="text" name="rows" id="rows"/></label> <br/><br />
<label># of Columns: <input type="text" name="columns" id="columns"/> </label><br/><br />
<input name="generate" type="button" value="Generate" onclick='createTable();'/><br /><br />
</form>
<div id="wrapper"></div>
如何获取此代码并将按钮添加到我的表中以选择某个单元格?
感谢您的反馈,我们非常感谢您的帮助!
答案 0 :(得分:0)
为每个单元格指定唯一ID。第1行单元格ID:11,12,13,...,1 n ;第2行单元格ID:21,22,23,...,2 n 。具有跟踪活动单元格(突出显示的单元格)的变量或对象属性。单击按钮,通过在单元格id的相应数字中添加或减去来获取相应单元格的ID。
例如:
<style>
#tab{
height: 102px;
width: 102px;
display:inline-block;
border:1px solid black;
background-color: white;
}
td{
border: .5px solid blue;
height: 20px;
width: 20px;
}
</style>
<body>
<div id ="main">
<table id="tab">
</table>
</div>
<button id="up">up</button>
<button id="down">down</button>
<script>
window.onload = function(){
function genGrid(n,m){
for (var i = 0; i<n;i++){
var row = document.createElement('tr')
row.id = "row"+i
for(var j=0; j<m;j++){
var cell = document.createElement('td')
cell.id = String(i+1)+String(j+1)
cell.innerText = cell.id
cell.style.color = "red"
row.appendChild(cell)
}
document.getElementById("tab").appendChild(row)
}
}
genGrid(4,4)
// manually choosing active cell and bg color
var activeCell = "11"
document.getElementById("11").style.backgroundColor = "yellow"
document.getElementById('up').onclick = function(){
var newId = parseInt(activeCell.slice(0,1))-1
if(newId > 0){
var oldCell =document.getElementById(activeCell)
oldCell.style.backgroundColor = "white"
var id = String(newId)+activeCell.slice(1,2)
var newCell = document.getElementById(id)
newCell.style.backgroundColor = "yellow"
activeCell = id
}
}
document.getElementById('down').onclick = function(){
var newId = parseInt(activeCell.slice(0,1))+1
var rowLength = document.getElementsByTagName('tr').length
if(newId <= rowLength){
var oldCell =document.getElementById(activeCell)
oldCell.style.backgroundColor = "white"
var id = String(newId)+activeCell.slice(1,2)
var newCell = document.getElementById(id)
newCell.style.backgroundColor = "yellow"
activeCell = id
}
}
}
</script>
</body>