首页 > 解决方案 > 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>

我没有收到任何错误,但第三列没有隐藏。

标签: javascriptjqueryhtml-tableshow-hide

解决方案


不要相信 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上的一篇旧博文中学到了这个技巧(他也感谢该页面上的其他一些博主)。


推荐阅读