我正在尝试在加载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>
我没有收到任何错误,但没有隐藏第三列。
不信任推迟确定DOM元素何时绘制到屏幕上。因为您使用的是let
,所以我假设您可以使用像onanimationstart
这样的现代JavaScript。您可以将其与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上的一个旧博客文章中学到了这个技巧(他也赞扬了该页面上的其他一些博客)。