javascript:将编号行添加到表中

javascript:将编号行添加到表中,javascript,dom,Javascript,Dom,我想向包含4个单元格的表中添加一行:indexnumber、firstname、lastname和points。作为Javascript的新手,我完全迷恋于textnodes、Child和其他Dom元素。谁可以帮助创建动态索引编号,如第一列中的1、2、3等 var-button=document.getElementById(“addRow”); button.onclick=addRowFunc; var firstName=document.getElementById(“firstN”)

我想向包含4个单元格的表中添加一行:indexnumber、firstname、lastname和points。作为Javascript的新手,我完全迷恋于textnodes、Child和其他Dom元素。谁可以帮助创建动态索引编号,如第一列中的1、2、3等

var-button=document.getElementById(“addRow”);
button.onclick=addRowFunc;
var firstName=document.getElementById(“firstN”);
var lastName=document.getElementById(“lastN”);
var points=document.getElementById(“pnt”);
函数addRowFunc(){
var tabel=document.getElementById(“myTable”);
变量行=tabel.insertRow(-1);
var cel1=行插入单元格(0);
var cel2=行插入单元格(1);
var cel3=行插入单元格(2);
var cel4=行插入单元格(3);
cel1.value=函数(){
对于(变量i=1;i

行数
名字
姓氏
要点



名字
姓氏
积分


添加
要插入新行,请使用append

<table id="mytable">
<tr><td >1</td> <td >sd</td> <td >sd</td> <td >sd</td></tr>
<tr><td >2</td> <td >sd</td> <td >sd</td> <td >sd</td></tr>
<tr><td >3</td> <td >sd</td> <td >sd</td> <td >sd</td></tr>
</table>

如果这是您想要的,请进行注释。

要插入新行,请使用append

<table id="mytable">
<tr><td >1</td> <td >sd</td> <td >sd</td> <td >sd</td></tr>
<tr><td >2</td> <td >sd</td> <td >sd</td> <td >sd</td></tr>
<tr><td >3</td> <td >sd</td> <td >sd</td> <td >sd</td></tr>
</table>

如果这是您想要的,请进行注释。

以下是获取节点和DOM工作方式的最简单方法:)

因此,假设您有一个数据数组,其格式如下:

data = [
    {
        indexNumber: 1,
        firstName: 'Bon',
        lastName: 'Jovi',
        points: 50,
    },
    {
        indexNumber: 2,
        firstName: 'Ann',
        lastName: 'Hathaway',
        points: 60,
    },
];
现在,您可以在
forEach
循环中处理此数组:

var table = document.getElementById('myTable');

data.forEach(function(element) {
    var row = document.createElement('tr');
    var cell1 = document.createElement('td');
    var cell2 = document.createElement('td');
    var cell3 = document.createElement('td');
    var cell4 = document.createElement('td');

    cell1.innerHTML = element.indexNumber;
    cell2.innerHTML = element.firstName;
    cell3.innerHTML = element.lastName;
    cell4.innerHTML = element.points;

    row.appendChild(cell1);
    row.appendChild(cell2);
    row.appendChild(cell3);
    row.appendChild(cell4);

    table.appendChild(row);
});

下面是了解节点和DOM如何工作的最简单方法:)

因此,假设您有一个数据数组,其格式如下:

data = [
    {
        indexNumber: 1,
        firstName: 'Bon',
        lastName: 'Jovi',
        points: 50,
    },
    {
        indexNumber: 2,
        firstName: 'Ann',
        lastName: 'Hathaway',
        points: 60,
    },
];
现在,您可以在
forEach
循环中处理此数组:

var table = document.getElementById('myTable');

data.forEach(function(element) {
    var row = document.createElement('tr');
    var cell1 = document.createElement('td');
    var cell2 = document.createElement('td');
    var cell3 = document.createElement('td');
    var cell4 = document.createElement('td');

    cell1.innerHTML = element.indexNumber;
    cell2.innerHTML = element.firstName;
    cell3.innerHTML = element.lastName;
    cell4.innerHTML = element.points;

    row.appendChild(cell1);
    row.appendChild(cell2);
    row.appendChild(cell3);
    row.appendChild(cell4);

    table.appendChild(row);
});

解决您面临的问题的一种方法是,使用CSS可以解决显示表格行元素的编号的问题,并遵循以下规则:

tbody {
  counter-reset: rownumber;
}
tr {
  counter-increment: rownumber;
}
td:first-child::before {
  content: counter(rownumber, decimal);
}
上面定义了计数器,
行号
,并通过
元素将其重置;因此,如果将行追加到多个
元素上,则每个
元素的后代将相互独立地编号。如果您希望对所有
元素进行连续计数,则只需将
计数器重置
规则向上移动到
元素,或移动到需要累积计数的任何其他(理想情况下是最接近的)祖先

该计数器在每个
元素中递增
1
,然后显示在每个
子元素的第一个
伪元素之前的
:。
counter()
的第二个参数是您希望使用的计数器类型(请参阅此答案了解(当前)可能的选项:(免责声明:这是我的答案之一,第二个代码片段将允许您查看不同计数器类型的结果)

因此,我也重写了这一部分——我想说是修订或重构,但这充其量只是轻描淡写——您将代码发布到以下函数中。注释中解释了代码:

// a named function to call:
function addRow() {

  // using 'let' to declare variables, this is mostly a
  // matter of personal preference in this case, and if
  // 'let' is unavailable to you, or your users, can be
  // replaced with 'var'.

  // here we define a 'details' Object to hold the
  // variables from the <input> elements we find
  // later:
  let details = {},

  // we use document.querySelector() to retrieve the first,
  // if any, elements matching the supplied CSS selector;
  // this is the element to which new content will be added:
    target = document.querySelector('#myTable tbody'),

  // and again we use document.querySelector() to find the
  // element we'll be cloning in order to append the new
  // new content:
    source = document.querySelector('#myTable tfoot tr.template')
      // we pass (Boolean) true as an argument in order to copy
      // the descendants of the cloned node as well as the node
      // itself:
      .cloneNode(true),

    // here we use Array.from() to convert the Array-like
    // HTMLCollection returned from document.querySelectorAll()
    // (which retrieves all the elements which match the
    // supplied CSS selector) into an Array:
    inputs = Array.from(
      document.querySelectorAll('form label input')
    );

  // we make use of the Array, via Array methods such as,
  // here, Array.prototype.forEach(), which iterates over
  // the elements of the Array:
  inputs.forEach(

    // using an Arrow function, rather than the traditional
    // anonymous function; here 'input' refers to the current
    // Array element of the Array of <input> elements over
    // which we're iterating.

    // here we update the details Object, by adding a new
    // key (details[input.id]) and setting the value of that
    // key to the value (input.value) held in the <input>:
    input => details[input.id] = input.value
  );

  // here we convert the Array-like NodeList of child-
  // elements of the source (the <tr> element we cloned
  // earlier) into an Array, again using Array.from, and
  // then iterating over those elements using, again,
  // Array.prototype.forEach():
  Array.from(source.children).forEach(

    // in this Arrow function we're naming the
    // current Array-element 'cell', the name is
    // purely a personal choice, and can be almost
    // anything, so long as it's valid in JavaScript.

    // here we set the text-content of the current
    // cell (<td> element) to be equivalent to the
    // value held in the details Object at the same
    // custom data-* attribute, here data-from, as
    // the current <td> (details.cell.dataset.from);
    // if there is no key of that name, we set the
    // text to an empty String (''):
    cell => cell.textContent = details[cell.dataset.from] || ''
  );

  // we append the newly modified <tr> element to
  // the target element (the <tbody>):
  target.appendChild(source);

  // and here we iterate over the <input> elements:
  inputs.forEach(

    // and set the value of each <input> back to
    // its default value, the value it held on
    // page-load in order to save the user having
    // to first delete existing content before
    // entering new content to add:
    input => input.value = input.defaultValue
  );
}

document.querySelector('#addRow').addEventListener('click', addRow);
正文{
框大小:边框框;
}
标签{
显示:块;
宽度:55%;
溢出:隐藏;
保证金:0.5em0;
}
桌子{
表布局:固定;
宽度:90%;
保证金:1em自动;
边界塌陷:塌陷;
}
标签输入{
宽度:50%;
浮动:对;
}
th,
运输署{
左边框:1px实心#000;
边框底部:1px实心#000;
线高:2米;
高度:2米;
}
th{
文本对齐:居中;
}
赛后{
内容:':';
}
td:第一个孩子,
第一个孩子{
左边框颜色:透明;
}
t车身{
计数器复位:行数;
}
tbody tr{
计数器增量:行数;
}
tbody td:第一个孩子::之前{
内容:计数器(行数、小数);
}
tfoot tr.template{
显示:无;
}

添加新的详细信息:
名字
姓氏
要点
添加
行数
名字
姓氏
要点

解决您面临的问题的一种方法是,使用CSS可以解决显示表格行元素编号的问题,并遵循以下规则:

tbody {
  counter-reset: rownumber;
}
tr {
  counter-increment: rownumber;
}
td:first-child::before {
  content: counter(rownumber, decimal);
}
上面定义了计数器,
rownumber
,并通过
元素将其重置;因此,如果将行追加到多个
元素上,则每个
的后代将彼此独立地编号。如果您希望连续计数所有
元素,则只需移动
>计数器重置
规则直到
元素,或任何其他(理想情况下是最接近的)祖先,您需要在其内进行累积计数

该计数器在每个
元素中递增
1
,然后显示在每个
子元素的第一个
伪元素之前的
:中。
counter()
的第二个参数是您希望使用的计数器类型(有关(当前)可能选项,请参阅此答案:(免责声明:这是我的答案之一,第二个片段将允许您查看不同计数器类型的结果)

因此,我也重写了这一部分——我想说是修订或重构,但这充其量只是轻描淡写——您将代码发布到以下函数中。注释中解释了代码:

// a named function to call:
function addRow() {

  // using 'let' to declare variables, this is mostly a
  // matter of personal preference in this case, and if
  // 'let' is unavailable to you, or your users, can be
  // replaced with 'var'.

  // here we define a 'details' Object to hold the
  // variables from the <input> elements we find
  // later:
  let details = {},

  // we use document.querySelector() to retrieve the first,
  // if any, elements matching the supplied CSS selector;
  // this is the element to which new content will be added:
    target = document.querySelector('#myTable tbody'),

  // and again we use document.querySelector() to find the
  // element we'll be cloning in order to append the new
  // new content:
    source = document.querySelector('#myTable tfoot tr.template')
      // we pass (Boolean) true as an argument in order to copy
      // the descendants of the cloned node as well as the node
      // itself:
      .cloneNode(true),

    // here we use Array.from() to convert the Array-like
    // HTMLCollection returned from document.querySelectorAll()
    // (which retrieves all the elements which match the
    // supplied CSS selector) into an Array:
    inputs = Array.from(
      document.querySelectorAll('form label input')
    );

  // we make use of the Array, via Array methods such as,
  // here, Array.prototype.forEach(), which iterates over
  // the elements of the Array:
  inputs.forEach(

    // using an Arrow function, rather than the traditional
    // anonymous function; here 'input' refers to the current
    // Array element of the Array of <input> elements over
    // which we're iterating.

    // here we update the details Object, by adding a new
    // key (details[input.id]) and setting the value of that
    // key to the value (input.value) held in the <input>:
    input => details[input.id] = input.value
  );

  // here we convert the Array-like NodeList of child-
  // elements of the source (the <tr> element we cloned
  // earlier) into an Array, again using Array.from, and
  // then iterating over those elements using, again,
  // Array.prototype.forEach():
  Array.from(source.children).forEach(

    // in this Arrow function we're naming the
    // current Array-element 'cell', the name is
    // purely a personal choice, and can be almost
    // anything, so long as it's valid in JavaScript.

    // here we set the text-content of the current
    // cell (<td> element) to be equivalent to the
    // value held in the details Object at the same
    // custom data-* attribute, here data-from, as
    // the current <td> (details.cell.dataset.from);
    // if there is no key of that name, we set the
    // text to an empty String (''):
    cell => cell.textContent = details[cell.dataset.from] || ''
  );

  // we append the newly modified <tr> element to
  // the target element (the <tbody>):
  target.appendChild(source);

  // and here we iterate over the <input> elements:
  inputs.forEach(

    // and set the value of each <input> back to
    // its default value, the value it held on
    // page-load in order to save the user having
    // to first delete existing content before
    // entering new content to add:
    input => input.value = input.defaultValue
  );
}

document.querySelector('#addRow').addEventListener('click', addRow);
正文{
框大小:边框框;
}
标签{
显示:块;
宽度:55%;
溢出:隐藏;
保证金:0.5em0;
}
桌子{
表布局:固定;
宽度:90%;
保证金:1em自动;
边界塌陷:塌陷;
}
标签输入{
宽度:50%;
浮动:对;
}
th,
运输署{
左边框:1px实心#000;
边框底部:1px实心#000;
线高:2米;
高度:2米;
}
th{
文本对齐:居中;
}
赛后{
内容:':';
}
td:第一个孩子,
第一个孩子{
左边框颜色:透明;
}
t车身{
计数器复位:行数;
}
t车身t