如何从动态构建的 table 中 select thead 元素?

How to select thead element from dynamically built table?

我在 JavaScript/JQUERY 中动态构建了 table。构建 table 后,我需要 select 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。该元素未 selected。我想知道如何访问 JavaScript 中动态构建的元素?我需要防止 headers 滚动,所以这就是我需要 select thead 元素 int he table 的原因。

您需要先将其附加到 dom,然后才能使用选择器

检索它

$(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>';
  $('#tableContainer').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='tableContainer'></div>

试试这个并在 $(document).ready() 之前调用 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>';

     $('#tableContainer').html(tbl)
 }

$(document).ready(function(){
   buildTbl();

   var test = $(document).find('#myTbl > thead');
   console.log(test);
});

并调用 ID 为 tableContainer

的 div

希望对您有所帮助

对于您的情况,我建议您使用另一种创建元素的方法。当您使用 jquery 时,您可以使用 jquery 创建您的 html 节点,这样您就可以在将其附加到 [=12= 之前访问您的 jquery 元素]:

$(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>