我在 JavaScript/JQUERY 中动态构建了表。构建表格后,我需要选择 thead
元素。这是我的代码示例:
$(document).ready(function(){
buildTbl();
});
function buildTbl() {
var tbl = '<table id="myTbl"><thead><tr><th>Column 1</th></tr></thead><tr><td>Cell 1</td></tr><tbody></tbody></table>';
$('#tblContainer').empty().append(tbl);
var test = $('#myTbl').find('thead');
console.log(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='tblContainer'></div>
正如您在控制台示例中看到的,长度是0
。未选择该元素。我想知道如何访问 JavaScript 中动态构建的元素?我需要防止标题滚动,这就是为什么我需要在表中选择 thead
元素。
最佳答案
根据您的情况,我建议您使用另一种创建元素的方法。当您使用 jquery 时,您可以使用 jquery 创建 html 节点,如下所示,以便您可以在将 jquery 元素附加到 dom
之前访问它:
$(document).ready(function(){
buildTbl();
});
function buildTbl() {
var $tbl = $("table").attr("id", "myTbl");
var $thead = $("thead");
// TODO: Here you can add your table rows into your thead
$tbl.append($thead);
// now you can access to your thead element without searching the dom.
console.log($thead);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
关于javascript - 如何从动态构建的表中选择ad元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53542067/