为何编辑器提示我的HTML表格多一个<tr>元素?作业要求仅需5个
表格
<tr>数量不符问题排查与解决 问题描述
作业要求表格包含5个<tr>元素,但系统检测显示有6个。手动计数代码中的<tr>标签确实是5个,相关代码如下:
<body> <table> <tr> <caption>Red Rocks, Colorado</caption> <th>Photo</th> <th>Date</th> <th>Description</th> </tr> <tr> <td> <img src="https://via.placeholder.com/50" alt="View from the top row; sitting area holds 9,525 people"> </td> <td>Jan 16,2018</td> <td>View from the top row; sitting area holds 9,525 people</td> </tr> <tr> <td> <img src="https://via.placeholder.com/50" alt="Facing south from the top of the amphitheater"> </td> <td>Feb 20, 2017</td> <td>Facing south from the top of the amphitheater</td> </tr> <tr> <td> <img src="https://via.placeholder.com/50" alt="Nearby red rocks sit 6,450 feet (1,970m) above sea level"> </td> <td>Mar 30, 2019</td> <td>Nearby red rocks sit 6,450 feet (1,970m) above sea level</td> </tr> <tr> <td colspan="5">Copyright @ 2023 Zippy Photographers</td> </tr> </table> </body>
问题原因
<caption>标签位置错误:它被嵌套在了第一个<tr>内部。根据HTML规范,<caption>是<table>的直接子元素,不能放在<tr>中。浏览器解析这种错误结构时会自动修正DOM,将<caption>移到<table>下,这个修正过程会生成额外的<tr>,导致系统检测到6个<tr>元素。
解决方案
将<caption>标签移到<table>内部、第一个<tr>之前,作为<table>的第一个子元素。同时修正最后一行的colspan值(表格实际只有3列,原colspan="5"不符合布局逻辑),修正后的代码如下:
<body> <table> <caption>Red Rocks, Colorado</caption> <tr> <th>Photo</th> <th>Date</th> <th>Description</th> </tr> <tr> <td> <img src="https://via.placeholder.com/50" alt="View from the top row; sitting area holds 9,525 people"> </td> <td>Jan 16,2018</td> <td>View from the top row; sitting area holds 9,525 people</td> </tr> <tr> <td> <img src="https://via.placeholder.com/50" alt="Facing south from the top of the amphitheater"> </td> <td>Feb 20, 2017</td> <td>Facing south from the top of the amphitheater</td> </tr> <tr> <td> <img src="https://via.placeholder.com/50" alt="Nearby red rocks sit 6,450 feet (1,970m) above sea level"> </td> <td>Mar 30, 2019</td> <td>Nearby red rocks sit 6,450 feet (1,970m) above sea level</td> </tr> <tr> <td colspan="3">Copyright @ 2023 Zippy Photographers</td> </tr> </table> </body>
内容的提问来源于stack exchange,提问作者Eli Steger
相关产品推荐
相关产品推荐

