将一行添加到用户动态创建的特定表中
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,
}));
}
});
我在页面上还有一个下拉列表,我最终希望能够隐藏所选表格旁边的所有表格。我想,一旦我弄清楚如何通过类将两者联系在一起,这就很简单了。
谢谢。如果你需要任何进一步的代码,请告诉我。
我刚刚找到了最接近的方法和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');
(在这种情况下最好使用)
相关文章:
- 如何在javascript中创建动态json对象
- 如何创建动态ajax提交表单
- 如何在javascript中创建动态正则表达式
- 如何使用pouchdb创建动态查询(couchdb可能也是如此)
- 如何在jquery mobile中使用json文件创建动态下拉菜单
- 基于所选下拉列表值创建动态复选框
- 使用推动创建动态对象
- 在浏览器窗口中创建动态灵活的分割标记
- 将字符串与integer连接,用作jquery中的变量(创建动态变量)
- 创建动态javascript对象
- 如何使用指令属性值创建动态模板
- 使用 JavaScript 创建动态下拉列表
- 如何在创建动态 HTML 页面时使用日期选择器
- 使用javascript中的append创建动态下拉列表
- Jquery - 创建动态名称选择器
- 如何根据查询字符串值创建动态超链接
- 使用javascript创建动态多维关联数组
- 使用javascript创建动态二级下拉列表
- 在JavaScript中创建动态绑定
- 在JS中创建动态对象