javascript - 如何使用 javascript 或 jquery 创建按钮的动态 tbody onclick
问题描述
我有这个代码:
$(document).ready(function() {
//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#myTable');
$('button').click(function() {
//Add row
table.append('<tr>\n\
<td><input name="product_name[]" type="text"/></td>\n\
<td><input name="qty[]" type="text"/></td>\n\
<td><input name="price[]" type="text"/></td>\n\
</tr>');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="row_no" type="text" placeholder="Type Your Number of row" />
<button>Add row</button>
<table id="myTable">
<tbody>
<tr>
<th class="column-title">Product name</th>
<th class="column-title">Quantity</th>
<th class="column-title">Price</th>
</tr>
</tbody>
</table>
当我单击按钮Add row时,它会在表中附加一行。
但是现在,我在 HTML 中有一个文本框。我想附加表以根据以下值生成行:
<input name="row_no" type="text" placeholder="Type Your Number of row" />
我如何实现这一目标?
解决方案
这是您要查找的内容:
$(document).ready(function() {
//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#myTable');
$('[name=row_no]').text();
$('button').click(function() {
var rows = $('[name=row_no]').val();
// If rows are at maximum 10,
if (!(rows > 10)) {
// then add rows
for (var i = 0; i < rows; i++) {
table.append('<tr>\n\
<td><input name="product_name[]" type="text"/></td>\n\
<td><input name="qty[]" type="text"/></td>\n\
<td><input name="price[]" type="text"/></td>\n\
</tr>');
}
}
else {
alert("Error: Too many rows!\n" +
"Maximum allowed: 10\n" +
"- Inserted: " + rows);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<input name="row_no" type="number" placeholder="Type Your Number of row" />
<button>Add row</button>
<table id="myTable">
<tbody>
<tr>
<th class="column-title">Product name</th>
<th class="column-title">Quantity</th>
<th class="column-title">Price</th>
</tr>
</tbody>
</table>
</body>
发生了什么变化?
- 您需要获取插入到文本字段中的值,这可以通过使用来实现,在这种情况下:
$('[name=row_no]').val();
,所以我将它作为rows
变量进行了评估,然后唯一要添加的是一个循环,该循环创建与用户插入一样多的行。 - 我也改成
<input name="row_no" type="text" placeholder="Type Your Number of row" />
了<input name="row_no" type="number" placeholder="Type Your Number of row" />
。
这个小改动允许用户只插入整数,这是一个很好的解决方案,可以避免因为编写一个新函数来验证插入的值而造成的时间损失。
编辑:
- 添加了关于用户可以在条件下插入多少行的控件
if (!(rows > 10))
(如果您需要更多或更少的行,唯一要编辑的是数字)
推荐阅读
- apache - Apache HTTP 服务器反向代理是否发送 SNI?
- python - 为什么我的操作没有改变价值?[班级]
- apache-kafka - 机器之间的Kafka分区滞后差异
- spring - 控制多个 JMS 队列的消耗
- arrays - 从 Google 表格中的函数仅返回一系列单元格(在所需的索引范围内)
- r - data.table 将输出分配给变量列
- android - Jetpack compose 打破 Room 编译器
- php - Codeigniter 计数 2 个表之间的关联记录
- javascript - React js - 将值传递给孩子到父母到另一个孩子
- sql - 如何将非唯一数据加载到主键 SQL