jQuery编辑<td>内容

时间:2020-08-13 16:09:41

标签: jquery

我想替换几个标记内的文本。我能够做到,但它会全部替换为第一场比赛。

jQuery代码是这样的:

var $boot = $('table > tbody > tr > td:nth-child(3):contains("(b)")');
$boot.html($boot.html().replace('(b)', ' <span class="b">(bootleg)</span>'));
.b {
  font-weight: bold;
  color: #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Year</th>
      <th>Comments</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>AAA</td>
      <td>2012</td>
      <td>CD (b)</td>
    </tr>
    <tr>
      <td>BB</td>
      <td>2013</td>
      <td>LP (b)</td>
    </tr>
    <tr>
      <td>CC</td>
      <td>2014</td>
      <td>CD</td>
    </tr>
    <tr>
      <td>DD</td>
      <td>2014</td>
      <td>CD</td>
    </tr>
    <tr>
      <td>EE</td>
      <td>2015</td>
      <td>LP (b)</td>
    </tr>
    <tr>
      <td>FF</td>
      <td>2017</td>
      <td>LP Box (b)</td>
    </tr>
    <tr>
      <td>GG</td>
      <td>2013</td>
      <td>CD</td>
    </tr>
    <tr>
      <td>LL</td>
      <td>2012</td>
      <td>2CD (b)</td>
    </tr>
  </tbody>
</table>

您可以在以下网址查看它:https://jsfiddle.net/wjqy0fe7/

输出为:

Title   Year    Comments
AAA 2012    CD (bootleg)
BB  2013    CD (bootleg)
CC  2014    CD
DD  2014    CD
EE  2015    CD (bootleg)
FF  2017    CD (bootleg)
GG  2013    CD
LL  2012    CD (bootleg)

我期望以下几点:

Title   Year    Comments
AAA 2012    CD (bootleg)
BB  2013    LP (bootleg)
CC  2014    CD
DD  2014    CD
EE  2015    LP (bootleg)
FF  2017    LP Box (bootleg)
GG  2013    CD
LL  2012    2CD (bootleg)

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

使用.each()遍历每个表单元格:

$('table > tbody > tr > td:nth-child(3):contains("(b)")').each(function() {
  $(this).html($(this).html().replace('(b)', ' <span class="b">(bootleg)</span>'));
})
.b {
  font-weight: bold;
  color: #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Year</th>
      <th>Comments</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>AAA</td>
      <td>2012</td>
      <td>CD (b)</td>
    </tr>
    <tr>
      <td>BB</td>
      <td>2013</td>
      <td>LP (b)</td>
    </tr>
    <tr>
      <td>CC</td>
      <td>2014</td>
      <td>CD</td>
    </tr>
    <tr>
      <td>DD</td>
      <td>2014</td>
      <td>CD</td>
    </tr>
    <tr>
      <td>EE</td>
      <td>2015</td>
      <td>LP (b)</td>
    </tr>
    <tr>
      <td>FF</td>
      <td>2017</td>
      <td>LP Box (b)</td>
    </tr>
    <tr>
      <td>GG</td>
      <td>2013</td>
      <td>CD</td>
    </tr>
    <tr>
      <td>LL</td>
      <td>2012</td>
      <td>2CD (b)</td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:0)

谢谢!!可行!

$('table > tbody > tr > td:nth-child(3):contains("(b)")').each(function() {
  $(this).html($(this).html().replace('(b)', ' <span class="b">(bootleg)</span>'));
})