如何使用Javascript和HTML DOM在表的特定单元格中显示数字
How can I display the numbers in specific cells of the table using Javascript and HTML DOM?
我解决了这个练习的一部分,从用户那里获取输入,onclick
按钮,它会动态创建表格。行数等于输入,列数是从用户那里获取的输入的两倍。但是我不知道如何在这样的某些单元格内显示数字。
参考
function createTable() {
var usrInput = document.getElementById('input').value;
var theader = '<table border="1">'n';
var tbody = '';
for (var i = 0; i < usrInput; i++) {
tbody += '<tr>';
for (var j = 0; j < 2 * usrInput; j++) {
tbody += '<td>';
tbody += '1' + i + ',' + j;
tbody += '</td>';
}
tbody += '</tr>';
}
var tfooter = '</table>';
document.getElementById('layer').innerHTML = theader + tbody + tfooter;
}
<!Doctype html>
<html>
<body>
<form>
<input type="text" id="input" />
<input type="button" value="Create Table" onclick='createTable()' />
<br/>
</form>
<div id="layer"></div>
</html>
你可以尝试这样的事情:
逻辑:
在矩阵中,您必须映射对角线,因此如果行和列相同,则row + column === length-1
一个。 -1
因为,循环从0
开始。第二个对角线将是row === column
.
在您的情况下,第一个对角线仍然有效。 对于另一个,您可以尝试column - length === row
或column-row === length
。
function createTable() {
var usrInput = document.getElementById('input').value;
var theader = '<table border="1">'n';
var tbody = '';
for (var i = 0; i < usrInput; i++) {
tbody += '<tr>';
for (var j = 0; j < 2 * usrInput; j++) {
tbody += '<td>';
if(((i+j) === usrInput-1) ||((j-i) === parseInt(usrInput)))
tbody += i+1;
else{
tbody += " ";
}
tbody += '</td>';
}
tbody += '</tr>';
}
var tfooter = '</table>';
document.getElementById('layer').innerHTML = theader + tbody + tfooter;
}
td{
width:20px;
height:20px;
}
<!Doctype html>
<html>
<body>
<form>
<input type="text" id="input" />
<input type="button" value="Create Table" onclick='createTable()' />
<br/>
</form>
<div id="layer"></div>
</html>
你可以试试这个,这是另一种解决方案
function createTable() {
var usrInput = document.getElementById('input').value;
var theader = '<table border="1">'n';
var tbody = '';
for (var i = 0; i < usrInput; i++) {
tbody += '<tr>';
for (var j=usrInput;j>0;j--) {
if (i == j-1) {
tbody += '<td>';
tbody += i+1 ;
tbody += '</td>';
} else {
tbody += '<td>';
tbody += "" ;
tbody += '</td>';
}
}
for (var j=0;j<usrInput;j++) {
if (i == j) {
tbody += '<td>';
tbody += i+1 ;
tbody += '</td>';
} else {
tbody += '<td>';
tbody += "" ;
tbody += '</td>';
}
}
tbody += '</tr>';
}
相关文章:
- 使用jquery在单击时在单元格中输入值
- CSS-若窗口太小,滚动条会出现在“表格”单元格上
- 可以'我不明白为什么;t将行和单元格添加到表中
- 如何在Angular中的表的所有单元格中添加链接
- 表中单元格的总和
- ExtJS网格单元格编辑器,防止焦点松动问题
- 有没有一种方法可以仅使用HTML/CSS来隐藏基于特定值的数据单元格
- 根据输入字段中键入的数字更改td单元格的颜色
- 如果随机数字是3-Javascript的倍数,则将表单元格更改为红色
- 如何使用Javascript和HTML DOM在表的特定单元格中显示数字
- 如何测试数组列中的单元格中的数字或字符串
- 如何只允许在jqGrid单元格编辑中使用数字
- 如何根据特定的表格单元格将数字缩减为文本输入框
- 如果value =<我可以让表格单元格有不同的背景颜色吗?使用jquery或PHP获取特定的数字
- 从表格单元格中选择值/文本/数字
- Javascript使用for循环累加器向表单元格id添加数字
- 如何在一定时间后将数字添加到表格单元格中
- 如何验证单元格在 spreadjs 中是否正好有 10 位数字
- 手控表 - 文本在数字单元格上对齐
- 确定行单元格中的最低数字