将数据附加到

时间:2016-04-04 21:53:11

标签: javascript html asp.net-mvc-5

我有一个表填充了数据库中的内容。用户应该能够在表格中添加任意数量的新条目(现在让我们忽略“保存”按钮。)

我尝试使用

向表中添加新行
$("#businesscategorytable tfoot").append(addNewRow);

其中addNewRow的格式与表中的其他行类似。但是,此过程不起作用。更令人困惑的是,在我正在进行的项目的单独页面中使用了类似的模块,一切都正常运行。

这是一个Stack Snippet,它提供了我正在使用的模型的简单模型:

    $(function() {
      //Remove Row Function for Business Category Tables
      $("table[id='businesscategorytable']").on("click", "input[id='btnDeleteRow']", function() {
        $(this).closest('tr').hide(); //hiding rows instead of removing so we only commit on 'Save'
      });
      //End Remove Row Function for Tables

      //Add Row Function for Business Category Tables
      $("input[id='btnAddBusinessRow']").click(function() {
        var addNewRow = "<tr><td style=\"display: none\"><input type=\"hidden\" class=\"hdnBusinessCatId\" id=\"hdnBusinessCatId" + idCount + "\" />" +
          "<td><input type=\"text\" id=\"businessCat" + idCount + "\" size=\"12\"></td>" +
          "<td><input type=\"text\" id=\"businessColor" + idCount + "\" size=\"8\" value=\"$\"></td>" +
          "<td><input type=\"button\" id=\"btnDeleteRow\" value=\"Delete\"\"></td>" +
          "</tr>";

        $("#businesscategorytable tfoot").append(addNewRow);
        idCount++;
      });
      //End Add Row Function
    });
<table border="1" id="businesscategorytable">
  <thead>
    <tr style="color:white;background-color:darkgray">
      <th>Category Name</th>
      <th>Color on Map</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="display: none">
        <input type="hidden" class="hdnBusinessCatId" id="0" />
      </td>
      <td>
        <input type="text" id="txtCategoryName0" size="12" value="0">
      </td>
      <td>
        <input type="text" id="txtCategoryId0" size="8" value="Red">
      </td>
      <td>
        <input type="button" id="btnDeleteRow" value="Delete">
      </td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td style="display: none">
        <input type="hidden" class="hdnBusinessCatId" id="hdnBusinessCatId0" />
      </td>
      <td>
        <input type="text" id="businessCat0" size="12" />
      </td>
      <td>
        <input type="text" id="businessColor0" value="$" size="8" />
      </td>
      <td>
        <input type="button" id="btnDeleteRow" value="Delete" />
      </td>
    </tr>
  </tfoot>
</table>
<input type="button" id="btnAddBusinessRow" value="Add" />

关于为什么这可能不起作用的任何想法?

1 个答案:

答案 0 :(得分:0)

如果您检查控制台,则可以看到idCountundefined,您需要在某处将idCount声明为变量。我做到了这一点似乎工作如何声明idCount取决于你,但它应该definitley不与你设置​​它的当前id冲突。 Here's a JS Bin。我刚刚在点击处理程序之前添加了var idCount=1。它可能在另一页上工作,因为在那里声明了idCount