将一行添加到用户动态创建的特定表中

add a row to a specific table created dynamically by user

本文关键字:创建 动态 用户 添加 一行      更新时间:2023-09-26

我正在创建一个网站来操作使用jquery创建的多个表上的数据。。。。大多数表在页面上时都会由用户添加。

我对jquery和javascript也很陌生,所以这里可能缺少一些基本的东西。

我已经能够将按钮与表头一起创建,然后将类添加到表和按钮中。我希望能够通过单击关联按钮向每个表添加可编辑的行和列,但无论是通过类还是其他方式,我都找不到将两者链接在一起的方法。

这是我添加表格的代码:

$("button.agentPerson").on("click", function() {
  var $newAgent = $('input.agentPerson').val();
  if ($('input.agentPerson').val() !== "") {
    $("div.commissionInfo").append("<br/><br/><table><tr><th>Address</th><th>Contract Date</th><th>Production</th></tr><button>New Deal</button></table><br/>");
    $("tbody:last-child").addClass($newAgent);
    $("button:last-child").addClass($newAgent);
    $("select.addToThis").append($('<option>', {
      value: $newAgent,
      text: $newAgent,
    }));
  }
});

我在页面上还有一个下拉列表,我最终希望能够隐藏所选表格旁边的所有表格。我想,一旦我弄清楚如何通过类将两者联系在一起,这就很简单了。

谢谢。如果你需要任何进一步的代码,请告诉我。

我刚刚找到了最接近的方法和parent方法,但我也无法使它们发挥作用。

这是我最近一次尝试获得一个附加到表的按钮。

$("body").on("click", "button", function(event) {
  var $theTable = $(this).closest("tbody");
  $theTable.append("<tr></tr><tr></tr><tr></tr>");
});

您可以这样做:

将当前$newAgent存储到按钮的data-table属性中
将当前$newAgent类添加到表中
然后,您可以通过data-table属性和类使用按钮来定位表。

var $newAgent;
$(".addTable").click(function(){
  if ( $('input.agentPerson').val() !== "" && $('input.agentPerson').val() !== $newAgent) {
    $newAgent = $('input.agentPerson').val();
    $("div.commissionInfo").append("<br/><br/><table class='"+$newAgent+"'><thead><tr><th>Address</th><th>Contract Date</th><th>Production</th></tr></thead><tbody></tbody></table><br/><button data-table='"+$newAgent+"' class='appendRow'>New Deal</button>");
    $("select.addToThis").append($('<option>', {
      value: $newAgent,
      text: $newAgent,
    }));
  }else{
    // throw an error if the field is empty or isn't updated after last table
    // alert for demo:
    alert('please update field!');
  }
})
$("body").on("click", "button.appendRow", function(event) {
  var $theTable = $("table."+$(this).attr('data-table')+" tbody");
  $theTable.append("<tr><td>blah</td><td>blah</td><td>blah</td></tr>");
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class=agentPerson value="blah"/>
<button type="button" class="addTable">Add table</button>
<div class="commissionInfo"></div>

外植体:

  • +(参考)用于将两个字符串合并到一起。类似'Hello ' + 'world'将等于'Hello world'
  • data-table(引用)只是元素的一个属性,与<table>元素无关(可以是data-something)。例如:data-something可通过以下方式访问:
    • $(element).data('something');(在某些情况下更有用)
    • $(element).attr('data-something');(在这种情况下最好使用)