javascript - 如何通过 jQuery 向表中添加行和列?
问题描述
我的页面上有下表:
<section class="content">
<div class="box">
<div class="box-header with-border">
<div class="row margin-bottom-20">
<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12 text-end">
<a href="#" title="Novo Cadastro" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#InsertProduct"> <i class="fa fa-plus"> </i>New </a>
</div>
</div>
</div>
</div>
<table class="table table-striped" id="QueryTable">
<thead>
<tr>
<th>Code: </th>
<th class="text-center">Name: </th>
<th class="text-center">Address: </th>
<th class="text-center">Phone: </th>
<th class="text-center">Options: </th>
</tr>
</thead>
<tbody>
<td>Code: </td>
<td class="text-center">Name: </td>
<td class="text-center">Address: </td>
<td class="text-center">Phone: </td>
<td class="text-center">Options: </td>
</tbody>
</table>
</section>
我需要通过 javascript 将行和列插入到这个表中。我试过类似的东西:
$('#QueryTable').find('tr').each(function(){
$(this).find('th').eq(n).after('<th>Test </th>');
});
我也试过
$('#QueryTable tr').append('<th>Test</th>')
我也试过02:
$('#QueryTable tr').each(function()
{
$(this).append('<th>Test</th>');
});
但是这些代码没有在我的表中插入行或列。如何通过javascript(纯或jquery)添加行和列?
解决方案
这是一个简单的例子。我首先修复了您的表格,以便您的单元格位于一行内:
//adds the new column
$('#QueryTable thead tr').append('<th>Test</th>');
//adds a new cell to all existing rows (this assumes that the newly added column does not exist)
//at initialization
$('#QueryTable tbody tr').each(function() {
$(this).append('<td>New Cell</td>');
});
//Adds a new row
$('#QueryTable tbody').append('<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-striped" id="QueryTable">
<thead>
<tr>
<th>Code: </th>
<th class="text-center">Name: </th>
<th class="text-center">Address: </th>
<th class="text-center">Phone: </th>
<th class="text-center">Options: </th>
</tr>
</thead>
<tbody>
<tr>
<td>Code: </td>
<td class="text-center">Name: </td>
<td class="text-center">Address: </td>
<td class="text-center">Phone: </td>
<td class="text-center">Options: </td>
</tr>
</tbody>
</table>
推荐阅读
- dart - 在颤振应用程序中尝试热重启时出现配置引擎错误
- magento2 - 修改数据库后magento2 megamenu无法保存
- python - 解析 LaTex 作者标签以提取作者姓名
- reactjs - react-native link - 超出最大调用堆栈大小
- shell - 如何编写遍历目录中文件的Makefile
- java - 使用 selenium 和虚拟电子邮件服务器测试重置密码功能
- android - 如何进行持久通知?
- macos - 无法将本地从站连接到 AWS 上的 Jenkins 主站
- powershell - 如何使用
收集关于 2 foreach 的信息 - c# - 如何启动异步任务对象