javascript - JQuery隐藏表格列
问题描述
我试图在加载内容后隐藏 html 表的特定列。表 html 是动态创建并使用 JQuery 加载的。这部分按预期工作。
let cur_grid = document.getElementById('grid1')
// table html is created.
let str_tbl_html = '<table id="tbl_grid1"><tbody><tr><td>1</td><td>2</td><td>3</td><td>4</td></tr><tr><td>1</td><td>2</td><td>3</td><td>4</td></tr></tbody></table>'
$.when($(cur_grid).html(str_tbl_html)).done(function() {
console.log('hide 3rd column')
$('#tbl_grid1 tr td:nth-child(3)').hide()
// also tried
$('#tbl_grid1').find('td:nth-child(3)').hide()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='grid1'></div>
我没有收到任何错误,但第三列没有隐藏。
解决方案
不要相信 Deferreds 可以确定 DOM 元素何时被绘制到屏幕上。由于您使用的是let
我假设您可以使用现代 JavaScript,例如onanimationstart
. 您可以将其与 CSS 动画一起使用来确定表格实际绘制的时间。
@keyframes any-animation {
from {opacity: 0.99;}
to {opacity: 1.0;}
}
table {
animation-name: any-animation;
animation-duration: 0.001s;
}
let cur_grid = document.getElementById('grid1')
// table html is created.
let str_tbl_html = '<table id="tbl_grid1" onanimationstart="hideThirdColumn()"><tbody><tr><td>1</td><td>2</td><td>3</td><td>4</td></tr><tr><td>1</td><td>2</td><td>3</td><td>4</td></tr></tbody></table>'
function hideThirdColumn() {
$('#tbl_grid1 tr td:nth-child(3)').hide()
};
我在css-tricks.com上的一篇旧博文中学到了这个技巧(他也感谢该页面上的其他一些博主)。
推荐阅读
- r - 如何限制 igraph/R 中最短路径的数量
- android - 移动应用程序的 Python REST API 登录/身份验证/授权
- javascript - 使用 Cypress 进行测试时如何拒绝警告框?
- python - 如何用 0 替换数组的某些元素?
- mysql - XAMPP 3.2.4 MySQL 启动后崩溃
- swift - UICollectionViewDiffableDataSource 自定义子类初始化
- python - 如何导出要重新导入的 pandas 数据透视表?
- javascript - Babel 编译失败:.presets[1][0] must be a string, object, function — 如何修复?
- c# - 引用 ASP.NET 项目文件夹中的文本文件
- python - Pygame 创建多个陨石并旋转它们