如何在下面的HTML输入文本框中添加序列号。
[只要用户单击生成表按钮,则在输入框中应显示序列号像1,2,3任何解决方案
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName('body')[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement('table');
var tblBody = document.createElement('tbody');
// creating all cells
for (var i = 0; i < 1; i++) {
var seqnumber = 1;
var seq = +1;
// creates a table row
var row2 = document.createElement('tr');
//====== table first row data =======//
var seq = document.createElement('td');
var seqText = document.createTextNode('Seq');
var l = document.createElement('td');
var seqText1 = document.createElement('input');
//===== seq generator =====//
seq.appendChild(seqText);
row2.appendChild(seq);
l.appendChild(seqText1);
row2.appendChild(l);
// add the row to the end of the table body
tblBody.appendChild(row2);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute('border', '2');
}
<input type="button" value="Generate a table." onclick="generate_table()" />
我的jsfiddle链接:https://jsfiddle.net/shreekantbatale2/bdwLuhgs/5/
我刚刚使用了counter
变量,这就是您所需要的吗?
var counter = 0;
function generate_table() {
counter++;
// get the reference for the body
var body = document.getElementsByTagName('body')[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement('table');
var tblBody = document.createElement('tbody');
// creating all cells
for (var i = 0; i < 1; i++) {
var seqnumber = 1;
var seq = +1;
// creates a table row
var row2 = document.createElement('tr');
//====== table first row data =======//
var seq = document.createElement('td');
var seqText = document.createTextNode('Seq');
var l = document.createElement('td');
var seqText1 = document.createElement('input');
seqText1.value = counter;
//===== seq generator =====//
seq.appendChild(seqText);
row2.appendChild(seq);
l.appendChild(seqText1);
row2.appendChild(l);
// add the row to the end of the table body
tblBody.appendChild(row2);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute('border', '2');
}
<input type="button" value="Generate a table." onclick="generate_table()" />