在N字数统计后在字符串内插入div而不破坏html

时间:2016-05-27 16:12:50

标签: javascript jquery

我正在尝试在文字段落中插入广告。

到目前为止,我已经写了这个(jsfiddle):

$(function() {
  var $article   = $('#post-text').html();
  var totalChars = $article.length;
  var breakChars = 300;
  if (totalChars > breakChars) {
    console.log(totalChars);
    var insertChars    = (breakChars - 10) + (totalChars - breakChars) * 0.2;
    var insertIndex    = $article.indexOf(' ', insertChars);
    var $articleWithAd = $article.substr(0,insertIndex) + '<div id="adPlayer">bla bla</div><p>' + $article.substr(insertIndex + 1);
    $('#post-text').html($articleWithAd);
  }
});

我计算文本的总字符长度。我设置了断点,这是我要插入广告的最小值,对于较小的文本,我根本不插入它。

我还使用百分比算法尝试根据总计数和最小计数将广告插入不同的位置。

这很有效,除非我遇到html标签,因为小提琴案例演示了如果我插入两个类class="class class2"之间的空间,所有的地狱都会松动......

我想使用我的代码,但要改进它以忽略html标记。

任何想法?

1 个答案:

答案 0 :(得分:0)

.text()替换为.html()。另外,<div>不是<p>元素的有效子元素,<p>不是<p>元素的有效子元素。

您可以使用.contents()来迭代.nodeValue的{​​{1}}或.innerHTML .childNodes,当#post-text到达时,insertIndexfor 1}}迭代节点和文本的循环,使用.before()$articleWithAd所在的节点之前插入insertText。请注意<span>处的<p>元素的已替换$articleWithAd元素。

&#13;
&#13;
$(function() {
      var elem = $('#post-text');
      var $article = elem.text();
      var totalChars = $article.length;
      var breakChars = 300;
      if (totalChars > breakChars) {
        console.log(totalChars);
        var insertChars = (breakChars - 10) + (totalChars - breakChars) * 0.2;
        var insertIndex = $article.indexOf(' ', insertChars);
        var $articleWithAd = '<span id="adPlayer" style="background:green">'
                             + 'bla bla<span>&nbsp;';
        var curr = null,
          n = 0;
    
        function countChars(el) {
          var text = el.nodeValue || el.innerHTML;
          iterateText: for (var i = 0; i < text.length; i++) {
            ++n;
            if (n === insertIndex) {
              curr = el;
              break iterateText;
            }
          };
          return curr
        }

        var elems = elem.contents();

        iterateNodes : for (var i = 0; i < elems.length; i++) {
          if (elems[i].childNodes.length) {
            for (var c = 0; c < elems[i].childNodes.length; c++) {
              if (countChars(elems[i].childNodes[c])) break iterateNodes;
            }
          }
        }
              
        console.log(curr, insertIndex, n);

        elem.find(curr).before($articleWithAd);

      }
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="post-text">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce eu accumsan dui. Sed molestie ac dolor venenatis tincidunt. Maecenas condimentum, diam at pellentesque pellentesque, massa dolor dignissim diam, nec mollis felis est non est. Vestibulum consectetur
    massa vel lectus porta, consequat venenatis odio pharetra. Integer a felis eget lectus tempus finibus nec a nulla. Nam leo metus, aliquet eleifend neque ut, tristique tristique mi. <a href="" class="asda asdasd asd asd asdasdasdsa sadasdasd asdasd asda asdasd asd asd asdasdasdsa sadasdasd asdasd asda asdasd asd asd asdasdasdsa sadasdasd asdasd ">Suspendisse potenti. Integer faucibus sollicitudin leo, vel ultrices nulla maximus vel.</a>    Vestibulum volutpat ligula sit amet nisi cursus aliquet. Quisque urna nisi, ullamcorper pretium volutpat non, porta non ligula. Integer nec turpis ut leo accumsan vestibulum.
  </p>
  <p>
    Nullam vitae orci metus. Nulla sit amet ipsum non sem tincidunt semper. Integer euismod dictum blandit. Vivamus eget molestie tellus, at porta purus. Duis vulputate, mi et fermentum aliquam, mi nisi convallis sapien, eu vehicula est mi et ex. Curabitur
    quam augue, tincidunt in orci ac, tempus imperdiet enim. Mauris nec sapien vehicula, vulputate lacus id, convallis urna. Aliquam tempor commodo erat.
  </p>
  <p>
    Morbi sit amet fermentum purus, ut pulvinar mi. Fusce nec sem enim. Fusce et nunc sodales mi dictum eleifend. Donec ornare molestie suscipit. Maecenas tempus urna nec elit aliquet, in iaculis augue malesuada. Cras vel imperdiet ante. Aenean nibh nibh,
    convallis vel arcu eget, placerat bibendum turpis.
  </p>
</div>
&#13;
&#13;
&#13;

jsfiddle https://jsfiddle.net/pv4m69jb/7/