如何从HTML表格中提取scope为row的Player列数据?
提取HTML表格中Player列的解决方案
你的HTML表格代码
<table> <caption>Alien football stars</caption> <tr> <th scope="col">Player</th> <th scope="col">Gloobles</th> <th scope="col">Za'taak</th> </tr> <tr> <th scope="row">TR-7</th> <td>7</td> <td>4,569</td> </tr> <tr> <th scope="row">Khiresh Odo</th> <td>7</td> <td>7,223</td> </tr> <tr> <th scope="row">Mia Oolong</th> <td>9</td> <td>6,219</td> </tr> </table>
原代码的问题
你写的jQuery代码无法工作,主要有两个问题:
- 选择器错误:你用了
#table tbody,但表格没有设置id="table",且原HTML里没有显式的<tbody>标签,导致选择器找不到目标元素。 - 标签选择错误:Player列的内容放在
<th scope="row">标签里,不是<td>,所以你找td的逻辑拿不到对应值。
正确的实现代码
以下两种方法都可以提取Player列的所有值:
方法一:通过属性筛选目标标签
直接筛选每行中scope="row"的<th>标签,精准获取Player列内容:
// 存储Player列值的数组 var playerList = []; $('table tr').each(function() { var playerTh = $(this).find('th[scope="row"]'); // 只处理包含Player的行(跳过表头) if (playerTh.length) { playerList.push(playerTh.text().trim()); } }); console.log(playerList); // 输出:["TR-7", "Khiresh Odo", "Mia Oolong"]
方法二:通过列位置筛选
利用Player列是每行第一个非表头的<th>的特点,跳过表头行后提取:
var playerList = []; // 跳过第一行表头,遍历数据行 $('table tr:not(:first)').each(function() { var playerName = $(this).find('th').eq(0).text().trim(); playerList.push(playerName); }); console.log(playerList); // 输出:["TR-7", "Khiresh Odo", "Mia Oolong"]
内容的提问来源于stack exchange,提问作者annd
相关产品推荐
相关产品推荐

