【问题标题】:Table not displayed表格未显示
【发布时间】:2018-09-08 05:52:22
【问题描述】:

我想按照下面代码中的方式显示表格,但不显示在屏幕上,代码仅使用 html 和 Javascript

<body id="page">
 <center>
    <table id="tables" border="1px" cellspacing="50px" style="margin-top:70px" >
    <script type="text/javascript">
     var row=2;

        for(var j=1;j<=2;j++){          
            $('#tables').append("<tr id='row"+j+"' style='margin-bottom:50px'>");
            for(var k=1;k<=5;k++){
                $("#row"+j).append("<td id='table"+k+"' class='button'  width='150' height='150' onclick='printBill("+k+")' background='images/green.png' align='center'>"+
                                            "<font size='+8'><b>"+k+"</b></font>"+
                                            "<br><font id='clock"+k+"' size='+1'> 0:0:0 </font>"+
                                        "</td>");
                }
            $('#tables').append("<tr id='row"+j+"' style='margin-bottom:50px'>");
        }

    </script>

    </table>
</center>
</body>

谁能帮忙找出这段代码有什么问题?

【问题讨论】:

  • 您的脚本在表对象中可能无济于事(因此可能找不到)...尝试放入 onload 触发函数
  • 我发现你的代码在这里运行良好:jsfiddle.net/6332Q你是否包含了 jQuery?
  • offtopic:你可以在桌子上用margin-left:auto; margin-right:auto;代替
  • 另外,如果你不想过早的精神错乱,你应该只创建一个具有相同 id 的元素 :)

标签: javascript html-table


【解决方案1】:

您可以使用两种典型的方式在页面加载时修改文档:

当 html 仍在加载时:

<table id="tables">
  <tbody>
    <script type="text/javascript">
      document.write('<tr>......</tr>');
    </script>
  </tbody>
</table>

在 html 页面加载之后(更具体地说,当 DOM 准备好时):

<table id="tables">
  <tbody>
  </tbody>
</table>
<script type="text/javascript">
  $(function(){ // see http://api.jquery.com/jQuery/#jQuery3
    // the full DOM is ready now, you can start modifying it.
    $('#tables > tbody').append('<tr>......</tr>');
  });
</script>

如您所见,我在table 和它的trs 之间插入了一个tbody 标记:浏览器通常会创建这个tbody 标记,即使您的源中不包含它。通过始终添加tbody(或thead/tfoot,如果您愿意)可以避免一些潜在的麻烦。

例如查看Can I rely on the implicit creation of the `tbody` tag? 或搜索implicit tbody

我稍微清理了你的代码:http://jsfiddle.net/6332Q/1/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多