截断文本,忽略子节点 javascript

truncating text, ignoring child nodes javascript

我正在尝试截断 div 中还包含 span 标记的字符串,但我的脚本正在收集 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);
        });

如果我没理解错你不想要这样的结果:

。 . .

但只有文字。

如果是这样你可以使用:

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);
  });
});
<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>

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

element.textContent: The Node.textContent property represents the text content of a node and its descendants

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;
  });
});
<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>

只是迭代文本节点:

$(".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) + "…";
      }
    }
  });
});
<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>