使用jQuery在第一行后加上方括号

时间:2019-07-14 00:08:55

标签: javascript jquery

我有这个

<p>
    <strong>FITZGERALD</strong> (CONT’D)<br>
    Shut up, boy, you don’t get no say in this.<br>
    (back to Henry)<br>
    And in case you hadn’t noticed, Captain, we’re seventeen men short of what we were.
    (off the wounded trapper)<br>
    Eighteen before long.
</p>

我想为.wi-dialog添加类p并将每个文本像( )一样放在括号<span class="wi-remark">( )</span>中,但是在第一个{ {1}}

所以我的段落看起来像这样

<br>

我无法解决第一行的问题。这是我的代码

<p class="wi-dialog">
    <strong>FITZGERALD</strong> (CONT’D)<br>
    Shut up, boy, you don’t get no say in this.<br>
    <span class="wi-remark">(back to Henry)</span><br>
    And in case you hadn’t noticed, Captain, we’re seventeen men short of what we were.
    <span class="wi-remark">(off the wounded trapper)</span><br>
    Eighteen before long.
</p>

1 个答案:

答案 0 :(得分:1)

这是我的解决方法。

$(document).ready(function(){
  var dialog = $( "p:has(strong)" ).addClass( "wi-dialog" );
  dialog.html(function(i, v) { return v.replace(/(?<=\n)\s*(\(.*?\)).*?/g, '<span class="wi-remark">$&</span>') });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  <strong>FITZGERALD</strong> (CONT’D)<br>
  Shut up, boy, you don’t get no say in this.<br>
  (back to Henry)<br>
  And in case you hadn’t noticed, Captain, we’re seventeen men short of what we were.
  (off the wounded trapper)<br>
  Eighteen before long.
</p>