增量变量td

时间:2018-02-18 15:41:52

标签: javascript html html-table

我在添加新的tr

时尝试增加var

<table id='myTable'>
    <tr> 
        <td id="count"></td>
        <td><select><option value="1">1</option></select></td>
        <!--obviously some more options-->
    </tr>
</table>
<button onclick="addfield()">Add</button>

脚本

<script>
var row = 1;

function addfield() {       
    document.getElementById("count").innerHTML = row;
    $("#myTable").find('tbody').append($('<tr>').append($('<td id="count">')).append($('<td><select><option value="1">1</option></select>')));
    row++;
}
</script>

正在发生的事情是,在添加新的&#39; tr&#39时,脚本正在递增第一个&t'id =&#34; count&#34;&#39; -Tag ; -Tag而不是递增下一个'td&#39; -Tag。此外,它不会显示新生成的&t'-Tag&#39; -Tag中的计数。 我错过了什么?

2 个答案:

答案 0 :(得分:0)

好的,首先让我继续说我搞砸了你的HTML结构,因为它让我觉得你正在使用一个表做一些不是表格的东西,所以我把结构改成了div。我还从你的脚本中逐渐增加并使用CSS计数器来获得相同的效果。如果使用表来保存你的数据是至关重要的,那么我想你不会选择这个答案。 HTML

<div id="myTable">
  <div class="row">
    <div class="cellish"><select><option value="1">1</option></select>
    </div>
  </div>
</div>
<button onclick="addfield()">Add</button>

CSS

body {
  counter-reset: count;
}
.cellish {
  display: inline-block;
}
.cellish::before {
  content: counter(count) " ";
  counter-increment: count;
}

JS

function addfield() {       
    $("#myTable").append($('<div class="row">')).append($('<div class="cellish"><select><option value="1">1</option></select>'));
}

答案 1 :(得分:-1)

您不应在html元素中多次使用相同的ID。 改变如下:

$("#myTable").find('tbody').append($('<tr>').append($('<td><select><option value="1">1</option></select>')));
相关问题