You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 12:32:13