如何基于地图区域点击显示/隐藏不同表格内容
实现点击地图区域显示对应表格
首先咱们先修正代码里的核心问题:你的事件监听目标错了,原来绑定的是.list-group a,但实际地图里的可点击元素是<area>标签,所以点击事件根本没触发。另外,初始状态要确保表格默认隐藏,这样交互才符合预期。
完整修正代码
HTML 部分
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <map class="list-group" name="map"> <area id="section-1" class="list-group-item" shape="rect" coords="198,368,142,337" href="#section-1" /> <!-- 可扩展更多区域,比如section-2 --> <area id="section-2" class="list-group-item" shape="rect" coords="300,368,242,337" href="#section-2" /> </map> <img alt="Placeholder Map" src="http://via.placeholder.com/680x466/444444/DDDDDD?text=Click+Areas" width="680" height="466" usemap="#map" /> <!-- 区域1对应的表格 --> <table class="section-table section-1" style="margin-left: auto; margin-right: auto; display: none;"> <tbody> <tr> <th><strong>Name </strong></th> <th><strong> Surname</strong></th> <th><strong>Address </strong></th> <th><strong>Postcode </strong></th> </tr> <tr> <td>test 1 </td> <td>test 1 </td> <td>test 1 </td> <td>test 1 </td> </tr> </tbody> </table> <!-- 区域2对应的表格 --> <table class="section-table section-2" style="margin-left: auto; margin-right: auto; display: none;"> <tbody> <tr> <th><strong>Name </strong></th> <th><strong> Surname</strong></th> <th><strong>Address </strong></th> <th><strong>Postcode </strong></th> </tr> <tr> <td>test 2 </td> <td>test 2 </td> <td>test 2 </td> <td>test 2 </td> </tr> </tbody> </table>
JavaScript 部分
$(function() { // 监听地图内所有area标签的点击事件 $('.list-group area').on('click', function(e) { e.preventDefault(); // 阻止href的默认跳转行为 // 先隐藏所有表格 $('.section-table').hide(); // 显示当前点击区域对应的表格 $('.' + this.id).show(); }); });
关键修改说明
- 修正事件绑定目标:把原来的
.list-group a改成.list-group area,这样才能正确捕捉地图区域的点击动作。 - 优化表格类名:用
section-table作为所有表格的通用类,方便批量控制隐藏;保留和区域ID对应的section-1、section-2类,实现精准显示。 - 默认隐藏表格:给表格加上
display: none,确保页面加载时表格不自动显示,符合点击触发的交互逻辑。 - 预留扩展空间:额外添加了
section-2的区域和表格示例,方便你后续快速扩展更多区域的内容展示。
这样修改后,点击不同的地图区域,就能对应显示各自的表格内容啦~
内容的提问来源于stack exchange,提问作者user7158897
相关产品推荐
相关产品推荐

