如何将名称属性添加到动态生成的 <tr>

How to add a name attribute to a dynamically generated <tr>

我一直在通过大量资源四处寻找,试图找到一种方法将 name="" 添加到生成的 table 行中。这是正在提交的表单的 table 部分。

<table id="quote_form_table"border="1" style="border-collapse:collapse;border:1px solid #000000;width:100%" cellpadding="3" cellspacing="3">
    <tr>
        <td>Quantity</td>
        <td>Item</td>
        <td>Unit Price</td>

        </tr>
        <tr name="row[]">
         <td><input type="text" name="quantity" ></td>
         <td>
           <select name="products">
              <option>Roller banner</option>
              <option>Grasshopper</option>
              <option>Pop up display</option>
            </select>
         </td>
        <td>
          <select name="type">
            <option>Roller banner</option>
            <option>Grasshopper</option>
            <option>Pop up display</option>
          </select>
      </td>
    </tr>
</table>
<br>
  <button type="button"onclick="addrow()">Add Row</button>
  <button type="button"onclick="removerow()">Remove Row</button><br><br><br>

这是添加和删除行的脚本。

   <script>
    function addrow() {
        var table = document.getElementById("quote_form_table");
        var row = table.insertRow(-1);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);

        cell1.innerHTML = '<input type="text" name="quantity" >';
        cell2.innerHTML = '<select name="products"><option>Roller banner</option><option>GrassHopper</option><option>Pop up display</option></select>';
        cell3.innerHTML = '<select name="type"><option>Roller banner</option><option>GrassHopper</option><option>Pop up display</option></select>';

    }
    function removerow() {
          document.getElementById("quote_form_table").deleteRow(-1);
    }
   </script>

作为 Javascript 的新手,(我使用术语 'novice' 非常宽松,因为它不是我自己熟悉的语言来解决这个问题),我尝试了 setAttribute 无济于事.

var tr = tr.setAttribute("name", "row[]", 0);

我找到了很多关于如何添加 类 或 Id 但 none 用于 'name' 的资源。因此,作为在黑暗中的野蛮刺杀,我尝试了最后一次尝试,看看我是否能解决这个问题。

row.name = "row[]";

所以现在我来了。

table 行被制作成数组供 PHP 处理,以便可以通过电子邮件发送信息以获取报价,我可以在另一端生成信息正确的顺序。

我的问题是如何将 name="row[]" 添加到动态生成的 tr 标签?

有可能吗?

您想将 name 添加到新行,对吗?

var numRow = 0;

function addrow() {
    var table = document.getElementById("quote_form_table");
    var row = table.insertRow(-1);
    row.setAttribute("name", "row"+numRow);
    numRow++;
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    cell1.innerHTML = '<input type="text" name="quantity" >';
    cell2.innerHTML = '<select name="products"><option>Roller banner</option><option>GrassHopper</option><option>Pop up display</option></select>';
    cell3.innerHTML = '<select name="type"><option>Roller banner</option><option>GrassHopper</option><option>Pop up display</option></select>';
}

function removerow() {
    document.getElementById("quote_form_table").deleteRow(-1);
    numRow--;
}

但我认为您应该使用 idclass 而不是 <tr> 元素的名称