[英]add a row to a specific table created dynamically by user
我正在创建一个站点来处理用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,
}));
}
});
我在页面上还有一个下拉菜单,我最终希望能够隐藏所选表旁边的所有表。 一旦弄清楚如何通过类将两者链接在一起,我就会觉得很简单。
谢谢。 如果您需要任何其他代码,请告诉我。
我刚刚找到了.closest和.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
:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.