【问题标题】:Increment my input text id when table row is cloned using Javascript使用 Javascript 克隆表行时增加我的输入文本 ID
【发布时间】:2013-06-14 14:33:56
【问题描述】:

我有一张表,它只包含一行。 Row 有很多元素,例如文本框和按钮。当我单击按钮时,表格行将使用append() 函数进行克隆。我的问题是当我单击按钮时,我想增加文本框和按钮 ID。我该怎么做?

示例 HTML:

<tr id="items:1">
    <td id="id">
        <input type="text" id="price:1" name="price" value="" size="6" readonly="readonly" />
    </td>
    <td id="id">
        <input type="text" id="quantity:1" name="quantity" size="10" align="middle" onblur="totalprice(this)" />
    </td>
    <td id="id">
        <input type="text" id="total:1" name="total" size="10" value="0" readonly="readonly" align="middle" />
    </td>
    <td id="id">
        <input type="button" onclick="cloneRow()" id="button:1" value="ADD" />
    </td>
</tr>

示例 JavaScript:

function cloneRow() {
    var row = document.getElementById("items:1");
    var table = document.getElementById("particulars");
    var clone = row.cloneNode(true);
    var rowId = "items:" + a.toString();
    clone.id = rowId;
    var tabledataid = document.getElementById("id");
    var inputtext = tabledataid.getElementsByTagName("input");
    var inputtextid = inputtext[a];
    var changeInputTextid = "price:" + b.toString();
    inputtextid.id = changeInputTextid;
    alert(changeInputTextid);
    table.appendChild(clone);
    a++;
}

【问题讨论】:

  • 告诉我们你有什么
  • 把你的代码放在有问题的地方,以便阅读

标签: javascript html


【解决方案1】:

一个fiddle

创建一个函数来添加行并正确使用文本框和列的索引

function insertRow() {
var x = document.getElementById('ttable');
var new_row = x.rows[0].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;

var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
x.appendChild(new_row);
}

【讨论】:

  • 您意识到您在第一次点击时获得了重复的行1?另外:为什么不使用rowIndex + 1(或其他合适的数字),而不是搜索行数?
  • @David 我想增加我的文本框 ID,你能告诉我如何使用 rowIndex+1
  • @DavidThomas 如果您检查它正在正确递增的 id,这只是文本。我已经纠正了小提琴
  • @Nullpointer 你是对的。我想改变原来的行 id 是可能的。
猜你喜欢
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 2015-05-10
  • 2015-09-28
  • 2015-12-13
相关资源
最近更新 更多