2016-09-06 87 views
0

我想截断也包含span标签的div内的字符串,但我的脚本收集span标签将其转换为文本并将其推回,如何忽略子标签中的数据。截断文本,忽略子节点javascript

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

回答

3

只是想迭代文本节点:

$(".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>

1

如果我理解正确你不想为结果:

<跨度类= “隐藏LG-UP” itemprop =“name”>。 。 。

但只是文字。

如果是这样,你可以使用:

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:该Node.textContent属性表示节点的文本内容和它的后代

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>

+0

''这是我想要截断的文本“.length == 40'不应该被截断为你的长度变量为50. –

+0

@JoseHermosillaRodrigo如果你仔细看看div的内容,你可能会看到新的行字符(即:\ n)和它们之间的隐藏空间。如何处理这些字符?它需要删除它们? – gaetanoM

+0

@JoseHermosillaRodrigo我只更新了完整的js代码片段,以及如何查看,使用空格删除无用的\ n,现在字符串不再被截断。但问题仍然存在:是对的?让我知道 – gaetanoM