HTML 和 JavaScript 自动递增编号 [英] HTML and JavaScript auto increment number

查看:17
本文介绍了HTML 和 JavaScript 自动递增编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 HTML 和 JavaScript 的新手.我在 HTML 中遇到了这样的问题(下面的代码只是将问题可视化以供您参考.)

I am new to HTML and JavaScript. I got a problem like this in HTML (This code below only visualize the problem for you to easy to reference.)

<tr>
    <td>1</td>
    <td>Harry</td>
</tr>
<tr>
    <td>2</td>
    <td>Simon</td>
</tr>
    <td>3</td>
    <td>Maria</td>
</tr>
</tr>
    <td>4</td>
    <td>Victory</td>
</tr>

这是一个名字列表,但问题是有时我需要在这个表中添加更多名字,我必须在数字 1 前面添加,所以这意味着我必须重新编写数字列表,(例如:1 1 2 3 4 --> 1 2 3 4 5).我觉得这不是一个好方法.

This is a name list, however the problem is that sometime i need to add more name into this table and I HAVE TO ADD in front of Number 1, so meaning i have to re-write the number list, (EX: 1 1 2 3 4 --> 1 2 3 4 5). I feel that is not a good way.

注意:我不想改变从上到下的列表编号减少.这是一个 HTML 文件,所以不能应用 PHP

NOTE: I don't want to change the list number decrease from top to bottom. And this is a HTML file so can't apply PHP

任何人都可以帮我把数字变成像i"这样的变量,一个函数可以帮我填充变量 i 从上到下自动递增

Anyone can help me to make the number to a variable like "i" and a function can help me to fill variable i increment from top to bottom automatically like

<tr>
    <td>i</td>
    <td>Harry</td>
</tr>
<tr>
    <td>i</td>
    <td>Simon</td>
</tr>
    <td>i</td>
    <td>Maria</td>
</tr>
</tr>
    <td>i</td>
    <td>Victory</td>
</tr>

以函数 Fill_i 为例:我认为在这种情况下应该使用 JavaScript.感谢您对这个问题的帮助和建议.

Function Fill_i for example: I think that JavaScript should be used in this case. Thanks for your help and suggestion on this problem.

再说一次:我不允许使用 PHP 或 ASP,当我添加新名称时,我是通过 HTML 手动添加的.

Again: I am not allowed to use PHP or ASP and when I add a new name, I add it manually by HTML.

推荐答案

这应该适合你:

<table>
  <tr>
    <td>Harry</td>
  </tr>
  <tr>
    <td>Simon</td>
  </tr>
  <tr>
    <td>Maria</td>
  </tr>
  <tr>
    <td>Victory</td>
  </tr>
</table>
<script>
    var tables = document.getElementsByTagName('table');
    var table = tables[tables.length - 1];
    var rows = table.rows;
    for(var i = 0, td; i < rows.length; i++){
        td = document.createElement('td');
        td.appendChild(document.createTextNode(i + 1));
        rows[i].insertBefore(td, rows[i].firstChild);
    }
</script>

脚本应立即放置在您的桌子之后.它遍历表格的每一行,并在该单元格内的递增数字的开头添加一个额外的单元格.

The script should be placed immediately after your table. It goes through each row of your table and adds an extra cell to the beginning with the incrementing number inside that cell.

JSFiddle 演示

这篇关于HTML 和 JavaScript 自动递增编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆