jQuery wrap()-正斜杠前的斜杠`/`

时间:2019-10-24 10:21:49

标签: javascript jquery

在斜杠/之前,我可以wrap()在HTML标记内的字符吗?我想将所有字符包装到/

之前的HTML元素中

jQuery代码段:

var x = jQuery('.elementor-drop-cap-yes p').contents().filter(function(){
  return this.nodeType === 3
}).wrap('<span class="drop-caps" />');

当前结果:

<p>
  <span class="a">
    <span class="b">1</span>
  </span>
  0/10
</p>

预期结果:

<p>
  <span class="a">
    <span class="b">1</span>
  </span>
  <div class="c">
    <b class="d">0</b>/10
  <div>
</p>

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以尝试以下简单的逻辑来实现html换行

jQuery(function(){
  jQuery('.elementor-drop-cap-yes p').each(function(){
     var $div = jQuery('<div/>');
     var $children = $(this).children();
     $div.append($children);
     var text = jQuery(this).text();
     if(text.indexOf('/')>=0) {
        var index = text.indexOf('/');
        //console.log(index);
        var textParts = text.substring(0, index);
        var newHTML = '<div class="c"><b class="d">' + text.substring(0, index) +'</b>' + text.substring(index, text.length) + '</div>';
        jQuery(this).empty().append($children).append(newHTML);
     }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="elementor-drop-cap-yes">
<p>
    <span class="a">
         <span class="b">1</span>
     </span>
    0/10
</p>
</div>