如何使用jQuery将td标签内的内容拆分为独立p标签
解决方法:拆分td内带逗号的p标签内容为独立p标签
直接使用以下jQuery代码即可实现需求:
$('td.value p').each(function() { const textContent = $(this).text().trim(); if (textContent.includes(',')) { const splitItems = textContent.split(',').map(item => item.trim()); const newPTags = splitItems.map(item => `<p>${item}</p>`).join(''); $(this).replaceWith(newPTags); } });
代码逻辑说明
- 选中所有带
.value类的td标签下的p元素,逐个遍历处理 - 取出p标签的文本内容并去除首尾空格,检查是否包含逗号
- 若存在逗号,按逗号分割文本,再将每个分割项的首尾空格去除
- 把每个处理后的文本项包裹成新的p标签,替换掉原来的单个p标签
原始HTML代码
<table class="shop_attributes"> <tbody> <tr> <th class="label">Ports</th> <td class="value"> <p>3 ports</p> </td> </tr> <tr> <th class="label">Types</th> <td class="value"> <p>1 VGA, 1 HDMI, 1 LAN</p> </td> </tr> </tbody> </table>
执行代码后得到的目标HTML
<table class="shop_attributes"> <tbody> <tr> <th class="label">Ports</th> <td class="value"> <p>3 ports</p> </td> </tr> <tr> <th class="label">Types</th> <td class="value"> <p>1 VGA</p> <p>1 HDMI</p> <p>1 LAN</p> </td> </tr> </tbody> </table>
内容的提问来源于stack exchange,提问作者Hadi
相关产品推荐
相关产品推荐

