仅显示#个单词并使用选项隐藏其余单词以进行更多切换

时间:2014-02-04 00:36:00

标签: javascript jquery

这里有一个jQuery问题。

我从数据库中提取数据并将其显示在div中。我的问题是,出于可用性目的,我只想显示前10个单词,或50个字符。 我的例子是:

<div>
    this is text pulled from the database and being displayed in this div
</div>

我想要实现的目标是:

<div>
    this is text pulled from the ...
</div>

其中...是一个切换按钮,用于在用户点击文本时显示其余文本。想法是为移动土地节省空间。这是可能吗?提前谢谢。

3 个答案:

答案 0 :(得分:3)

您可以将完整值存储在data-*变量中并连接点击事件,以便在点击时显示完整值。

一个有效的例子是http://jsfiddle.net/R7DeS/

<div id="divData" data-full-content="this is text pulled from the database and being displayed in this div">
    this is text pulled from the ...
</div>

您的js将如下所示。

$(function(){

    $("#divData").on("click", function(){

        var str = $("#divData").data("full-content");

        $("#divData").html(str);


    });

});

当然,您可以选择从其他地方获取完整数据。我只是使用data-*选项来简化它。

答案 1 :(得分:1)

function truncate($elem, wordNum){
    var words = $elem.text().trim().split(/\s/).slice(0,wordNum);
    var replacement = $("<div/>").text(words.join(" ") + "...");
    replacement.click(function(){
        $(this).hide();
        $elem.show();

    });
    $elem.click(function(){
        replacement.show();
        $elem.hide();
    });

    $elem.before(replacement);
    $elem.hide();
}

truncate($("div"), 5);

JS小提琴: http://jsfiddle.net/aAeV8/2/

答案 2 :(得分:1)

Scartag给了你天才数据 - *的想法。这是我将来可能需要使用的一个很棒的功能。

在选择前x个单词方面,我会在字符串上使用正则表达式和.exec()函数,并使用exec在<div>中给出的数字输出子字符串。

例如,

(?:\w+\s+){4}将选择前4个单词。