在切换中更改文本范围的值

时间:2013-12-06 00:21:32

标签: jquery

$('.post-content').each(function () {
    var count = $(this).children().length;
    if (count > 1) {
        $(this).append("<span class='more'>More</span>");
        sel = $(this).children('p').slice(2);
        sel.hide();
    }
});


$(".more").click(function () {
    more = $(this);
    sel = $(this).parent().children('p').slice(2);
    console.log($(this))
    sel.slideToggle(function () {
        more.text("More");
    }, function () {
        more.text("Less");
    });
});

此代码工作正常,除非我尝试更改/更少。应该更多 - &gt;少 - &gt;更多,我有更多 - &gt;少 - &gt;少

演示

http://jsfiddle.net/Y6TaU/

2 个答案:

答案 0 :(得分:5)

有两点需要注意:1。slideToggle()需要1个完整的回调2.这将对sel中的每个元素执行。您需要执行单个回调函数,在完成所有幻灯片操作时,您将切换文本。

对于切换文本,您可以使用.text(function).text()变体,在您可以使用动画返回的promise()之后执行单个回调。

$(".more").click(function () {
    var more = $(this);
    sel = $(this).parent().children('p').slice(2);
    sel.stop(true, true).slideToggle().promise().done(function () {
        more.text(function (_, text) {
            return text == "More" ? 'Less' : "More"
        });
    });
});

演示:Fiddle

答案 1 :(得分:0)

请参阅jQuery documentation

.slideToggle( [duration ] [, complete ] )

第一个参数应该是持续时间,第二个参数应该是回调。您需要明确检查more的当前内容,并根据该决定做出决定。

相关问题