在一定数量的字符后在p内添加span标记

时间:2014-10-15 08:10:29

标签: javascript jquery html

假设你的HTML有这个:

<div class="contentBox"> 
    <p>I have some content that is good to read</p>
</div>

但是你想在一定数量的字符之后添加一个span标签,比方说26个字符,这些字符就在&#34;&#34;之后。结果如下:

<div class="contentBox">
    <p>I have some content that<span> is good to read</span></p>
</div>

必须在一定数量的字符之后,因为段落会不时变化。

4 个答案:

答案 0 :(得分:4)

在您想要设置span后设置字符数。获取p元素的文本。子字符串从开始到字符数量,添加span,继续其余并添加结束span

尝试:

var after=26;
var html = $(".contentBox p").html();
html = html.substring(0, after) + "<span>" + html.substring(after)+"</span>";
$(".contentBox p").html(html);

<强> DEMO

答案 1 :(得分:2)

String.prototype.insertTextAtIndices = function (text) {
    return this.replace(/./g, function (char, index) {
        return text[index] ? text[index] + char : char;
    });
};
//usage
var range = {
    25: "<span style='color:red'>",
    40: "</span>"
};

document.getElementsByTagName("p")[0].innerHTML = document.getElementsByTagName("p")[0].innerHTML.insertTextAtIndices(range);

http://jsfiddle.net/4zx37Lhm/1/

答案 2 :(得分:1)

您可以使用JavaScript's substr method

function addSpan($elems) {
  $elems.each(function() {
      var $elem = $(this),
          text = $elem.text();

      if (text.length <= 25)
        return;

      var start = text.substr(0, 25),         // "I have some content that "
          end = text.substr(25, text.length); // "is good to read"

      $elem.html(start + '<span>' + end + '</span>');
  });
}

addSpan($('.contentBox').find('p'));
span {
  color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="contentBox"> 
  <p>I have some content that is good to read</p>
</div>

<div class="contentBox"> 
  <p>I have some content that is good to read and this is a much longer string!</p>
</div>

答案 3 :(得分:1)

尝试此操作:使用substring()获取字符串的第一部分和第二部分,并使用span元素修改文本,将其放入html p标记的p

下面的函数将迭代contentBox div下的所有.each(),但如果您只定位一个div,则可以在不使用$(function(){ $('.contentBox p').each(function(){ var text = $(this).text(); var first = text.substring(0,26); var second = text.substring(26,text.length); $(this).html(first + '<span>' + second + '</span>'); }); });

的情况下使用它
{{1}}

<强> DEMO