试图缩短文本主体,其中可能有链接

Trying to shorten a body of text that may have links in it

本文关键字:可能有 链接 主体 文本      更新时间:2023-09-26

我想找出一种方法来缩短可能包含链接的文本体。

<div class="bio">
    Banjo my soundcloud is <a href="http://soundcloud.com/username">http://soundcloud.com/username</a>
    Echo Park kale chips blog, cred pitchfork keffiyeh mixtape tumblr photo booth artisan helvetica
    meggings fashion axe roof party. Aesthetic biodiesel direct trade butcher, iPhone occupy before
    they sold out trust fund mumblecore cornhole food truck DIY narwhal freegan. Salvia try-hard
    freegan, Brooklyn Marfa craft beer fanny pack dreamcatcher High Life irony sriracha. Mumblecore
    Terry Richardson ethnic, pop-up tattooed sartorial 3 wolf moon banjo biodiesel church-key semiotics
    polaroid Etsy Schlitz hashtag. Wes Anderson gluten-free lomo brunch, raw denim plaid Schlitz salvia. 
</div>

我最初尝试通过截断字符数来缩短文本主体,之后我将插入一个"more"链接,将其余文本放在一个跨度中,并隐藏跨度,直到单击"more"链接。但是,如果用户决定将链接放在错误的位置,则插入'more'链接会破坏用户放入的锚标记。

这是我找到的解决工作的方法:http://www.bookofzeus.com/articles/dynamically-shortened-text-using-jquery/

什么是缩短文本正文的好方法,可能有锚标记在里面?

你是对的,jquery演示代码不工作,但演示可以。我不得不修理一些东西,但这是一个你可以看到的小提琴。我也用了你的短信信息。

http://jsfiddle.net/Fyzxn/1/

$(document).ready(function() {
    var orgContent = $('.bio').html();
    var txtContent = $('.bio').text().substr(0, 50) + '... <a id="morelink">more</a>';
    $('.bio').html(txtContent);
    $("body").on("click", '#morelink', function(){
        $('.bio').html(orgContent);
        $('<a id="lesslink"> less</a>').appendTo('.bio');
    });
    $("body").on("click", '#lesslink', function(){
        $('.bio').html(txtContent);
    });
});

我能想到的最简单的方法是动态地创建文本主体的纯文本版本,这将作为预览显示。这样,您就不会有截断任何标记的问题,因为您将只处理纯文本。

jQuery的text()方法可以用来移除字符串中的所有HTML标签。这样,您就可以创建一个纯文本预览,并在用户单击"more"链接
时显示实际内容和HTML标记。