截断文本,忽略子节点javascript

时间:2016-09-06 16:48:09

标签: javascript truncate

我试图在包含span标记的div中截断字符串,但我的脚本正在收集span标记,将其转换为文本并将其推回,如何忽略子数据标签

HTML:

<div class="oo-roboto-override row-title">
    <span class="hidden-lg-up" itemprop="name">
        Title: 
    </span>
    This is the text that I want to truncate
</div>

使用Javascript:

        $(".row-title").each( function() {
            var g = (this).innerHTML;
            var x = ". . . ";
            var leng = 50;
            var html = g.substring(0, leng)+"";
            var allHTML = html+x;
            $(this).text(allHTML);
        });

2 个答案:

答案 0 :(得分:3)

只需迭代文本节点:

&#13;
&#13;
$(".row-title").each(function() {
  var leng = 25;
  [].forEach.call(this.childNodes, function(child) {
    if(child.nodeType === 3) { // text node
      var txt = child.textContent.trim();
      if(txt.length > leng) {
        child.textContent = txt.substr(0, leng) + "…";
      }
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="oo-roboto-override row-title">
  <span class="hidden-lg-up" itemprop="name">
    Title: 
  </span>
  This is the text that I want to truncate
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果我理解正确,你不希望结果:

&lt; span class =“hidden-lg-up”itemprop =“name”&gt; 。 。

但只有文字。

如果是这样你可以使用:

double (*buffer)[cols] = malloc(sizeof(*buffer) * rows); /* VLA (since C99) */

摘录:

var g = $(this).text();
$(function () {
  $(".row-title").each( function() {
    var g = $(this).text().trim();
    var x = ". . . ";
    var leng = 50;
    var html = g.substring(0, leng)+"";
    var allHTML = html+x;
    $(this).text(allHTML);
  });
});

因为这个问题被标记为javaScript,所以这是完整的js:

中的片段
  

element.textContent:Node.textContent属性表示节点及其后代的文本内容

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<div class="oo-roboto-override row-title">
    <span class="hidden-lg-up" itemprop="name">
        Title:
    </span>
    This is the text that I want to truncate
</div>
window.addEventListener('DOMContentLoaded', function(e) {
  [].forEach.call(document.getElementsByClassName('row-title'), function(element, index) {
    var g = element.textContent.trim().replace(/\n */g, '');
    var x = ". . . ";
    var leng = 50;
    var html = g.substring(0, leng)+"";
    var allHTML = html+x;
    element.textContent = allHTML;
  });
});