在前端页面的表格交互场景中,经常需要动态获取某一行或者多行表格里的特定字符串,比如提取选中行的用户ID、订单编号等信息,jQuery的DOM操作能力可以高效完成这类需求。

实现核心思路
整个操作可以拆分为三个核心步骤:首先通过jQuery选择器定位到目标表格行,可以是选中的行、特定索引的行或者符合自定义条件的行;接着遍历行内的单元格元素,获取每个单元格的文本内容;最后对获取到的文本进行匹配判断,筛选出符合要求的特定字符串。
基础实现示例
假设我们有一个用户列表表格,需要获取选中行的用户邮箱字符串,表格结构如下:
<table id="userTable" border="1">
<thead>
<tr>
<th>选择</th>
<th>用户名</th>
<th>邮箱</th>
<th>手机号</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="rowCheck"></td>
<td>张三</td>
<td>zhangsan@ipipp.com</td>
<td>13800138000</td>
</tr>
<tr>
<td><input type="checkbox" class="rowCheck"></td>
<td>李四</td>
<td>lisi@ipipp.com</td>
<td>13900139000</td>
</tr>
</tbody>
</table>
<button id="getEmailBtn">获取选中行邮箱</button>对应的jQuery实现代码如下:
$(function() {
// 给按钮绑定点击事件
$('#getEmailBtn').on('click', function() {
// 存储提取到的邮箱字符串的数组
let targetEmails = [];
// 遍历所有选中的复选框对应的行
$('.rowCheck:checked').each(function() {
// 获取当前复选框所在的行元素
let currentRow = $(this).closest('tr');
// 获取行内第三个单元格(邮箱列)的文本内容
let emailText = currentRow.find('td').eq(2).text().trim();
// 简单的邮箱格式校验 匹配包含@的字符串
if (emailText.indexOf('@') !== -1) {
targetEmails.push(emailText);
}
});
// 输出提取结果
if (targetEmails.length > 0) {
console.log('提取到的邮箱:', targetEmails);
alert('提取到的邮箱:' + targetEmails.join(','));
} else {
alert('请先选中包含有效邮箱的行');
}
});
});按条件匹配特定字符串
如果需要提取的不是固定列的内容,而是行内所有单元格中符合特定规则的字符串,比如提取所有以138开头的手机号,可以调整遍历逻辑:
function getTargetStringFromRow(rowElement, pattern) {
let result = [];
// 遍历行内所有单元格
rowElement.find('td').each(function() {
let cellText = $(this).text().trim();
// 使用正则匹配目标字符串
let match = cellText.match(pattern);
if (match) {
result.push(match[0]);
}
});
return result;
}
// 使用示例 提取第一行中138开头的手机号
let firstRow = $('#userTable tbody tr').eq(0);
let phonePattern = /^138\d{8}$/;
let matchedPhones = getTargetStringFromRow(firstRow, phonePattern);
console.log('匹配到的手机号:', matchedPhones);注意事项
- 获取文本内容时建议使用
text()方法,避免html()方法获取到多余的HTML标签内容 - 如果表格是动态渲染的,需要把事件绑定放在表格渲染完成之后,或者使用事件委托的方式绑定事件
- 对提取到的字符串做匹配时,建议先调用
trim()方法去除首尾空格,避免出现匹配误差 - 如果目标字符串包含特殊字符,正则匹配时需要做对应的转义处理