Javascript: table 布局在使用 innerHTML 时被忽略

Javascript: table layout is ignored when using innerHTML

当我使用 Javascript 在网页上放置一些 table 标签时,显示的文本忽略了 table 标签。它只是将文本并排放置,而不是按列显示。

这张图显示的是什么: 蓝色是 headers 列,黑色是 table 内容。如您所见,table 内容不在 headers...

列之后

这是 Javascript 代码的相关部分:

document.getElementById("searchresults").innerHTML = 
  '<div class="table-row"> 
   <div class="table-cell">114</div>
   <div class="table-cell">GebouwEigenaar</div>
   <div class="table-cell">Paleis het Loo</div>
   <div class="table-cell">Begane Grond</div>
   <div class="table-cell">Koffiecorner 1</div>
   <div class="table-cell">Kantoorruimte</div>
   </div>';

这是相关的 HTML 代码:

<div id="searchresults"></div>

用于显示 table 行和单元格的 CSS 在 Web 应用程序的其他地方使用时没有问题。也是用来显示列headers这样的:

<div class="table-row-header">
  <div class="table-cell col-2" >Sticker-ID</div>
  <div class="table-cell col-2" >Gebouweigenaar</div>
  <div class="table-cell col-2" >Gebouw</div>
  <div class="table-cell col-2" >Verdieping</div>
  <div class="table-cell col-2" >Ruimte</div>
  <div class="table-cell col-2" >Ruimtefunctie</div
</div>

CSS代码:

.table { display: table; width: 100%; border-collapse: collapse;}
.table-row { display: table-row; width: 100%; cursor: pointer; position: relative; margin-top: 20px;}
.table-row:nth-child(even) { background: #fafafa; }
.table-row:nth-child(odd) { background: white; }
.table-row-header { display: table-row; width: 100%; color: #0867b3; border-bottom: 1px solid #d7d7d7; background: white; }
.table-cell {display: table-cell; padding: 10px 10px; position: relative; }
.table-cell span { display: none; font-weight: bold; }
.col-2  { width: 16.66%; }

浏览器似乎没有呈现 JavaScript 插入的 HTML。 但为什么会这样...?

我尝试用 .value 替换 .innerHTML,但没有显示任何内容。
任何建议都非常感谢。 谢谢!

有些东西阻止了您的 table 行和 table 单元格获取它们的 .css 属性。在不了解您的 .css 文件和周围环境的情况下,很难猜出原因。但作为表面层面的猜测,请考虑查看

1) 您的 table cell/row css 属性未正确导入。

2) 您的 parent table 的 css 属性是否覆盖了 children 的属性。

作为提示,您应该尝试将这些 div 粘贴到 table 的上下文之外。 css 样式会自动显示吗?如果是这样,您现在知道它与 parent div 有关。如果不是,您知道问题出在 child div。

问题已解决。 这是由于 table 格式标签使用不当造成的。 这导致格式不正确。 感谢大家提供的建议!