我试图在加载 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 上的一篇旧博客文章中学到了这个技巧。 (他还赞扬了该页面上的其他一些博主)。
关于javascript - JQuery隐藏表格列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60708168/