截断文本而不点击嵌套链接

Truncate text without hitting nested link

本文关键字:嵌套 链接 文本      更新时间:2023-09-26

我的段落嵌套了一个阅读更多链接。

<p>Lorem ipsum blah blah blah <a href="link">Read More</a></p>

我需要截断段落文本并以省略号结束它,而不会影响 <a></a> 标记中的任何内容。

我可以使用$(p).text($(p).text().substring(0,n)+'...');截断文本,但当然,如果我使用$(p).text()抓取段落,它将包含链接并将其删除。

有没有办法抓取,然后用截断的版本替换<p>的文本,而不影响</a>.最好不必使用任何正则表达式或克隆链接并重新附加它?

您可以使用

nodeType 执行类似操作。然后,您可以使用textContent属性更改值。

对于文本节点,nodeType 属性将返回 3。

alert($('p').contents().filter(function() {
  return this.nodeType == 3;
})[0].textContent);
//set new value
$('p').contents().filter(function() {
  return this.nodeType == 3;
})[0].textContent = 'New text ';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>Lorem ipsum blah blah blah <a href="link">Read More</a></p>

$(function() {
  
  var x = $("p").contents().get(0).nodeValue; // This will grab the text ignoring the other nodes:
  $("p").html(x.substring(0, 5) + '...' + $("p").find("a").wrap("<p>").parent().html()); // Setting x and appending the <a> html
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum blah blah blah <a href="link">Read More</a>
</p>

您可以尝试以下脚本:

 $(document).ready(function () {
        var hrefTag = $('a').attr('href');   
        $('p').html('<a href="' + hrefTag + '">Read More</a>');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum blah blah blah <a href="link">Read More</a></p>