jQuery 改变附加点击事件

4
我有以下jQuery代码,可以定位页面上的ul元素,在该ul元素中隐藏第三个后的所有li项,并添加一个"显示更多!"文本链接,当单击时,可以显示/切换隐藏的列表项。
$('ul')
    .find('li:gt(2)')
    .hide()
    .end()
    .append(
        $('<li>Show More!</li>').click( function(){
        $(this).siblings().toggle(500);
        })
    );
脚本功能示例:http://jsfiddle.net/vf6j5/

这是我希望脚本实现的功能:当点击“显示更多”后,展现隐藏元素时,我希望“显示更多”的文本被替换为“显示较少”。这样做会更加用户友好并且更有意义。

你有什么想法可以实现这个功能吗?


可能是Button text toggle in jquery的重复问题。 - epascarello
6个回答

5

http://jsfiddle.net/vf6j5/2/

$('ul')
    .find('li:gt(2)')
    .hide()
    .end()
    .append(
        $('<li>Show More!</li>').click(function() {
            var txt = $(this).text() == "Show More!" ? "Show Less!" : "Show More!";
            $(this).text(txt).siblings(':gt(2)').toggle(500);
        })
    );​

这是唯一一个只切换“额外”项目而不切换前三个的答案。 - Shmiddty

5

看这里:

$('ul')
        .find('li:gt(2)')
         .hide()
        .end()
        .append(
            $('<li class="title">Show More!</li>').click( function(){
            $(this).siblings().toggle(500);
                $(".title").html() === "Show More!"
                    ? $(".title").html("Show Less!")
                    : $(".title").html("Show More!")

            })
        );

已测试代码


如果有多个.title元素怎么办? - Shmiddty
然后我们需要修改代码。在这种情况下,那段代码运行良好。如果你需要帮助,请给我看一下你的问题示例。 - WooCaSh
仅仅因为你需要根据外部因素来改变它,就表明这个解决方案是不好的。 - Shmiddty

4
$('ul').find('li:gt(2)').hide().end().append(
$('<li>Show More!</li>').click(function() {
    var $this = $(this);
    $this.siblings().toggle(500);
    $this.text(function(i, t) {
        return t === 'Show More!' ? 'Show Less!' : 'Show More!'
    })
}));

http://jsfiddle.net/aGeMp/


3
$('ul').find('li:gt(2)')
       .hide()
       .end()
       .append(
         $('<li>Show More!</li>').click(function() {
            $(this).text($(this).prev('li').is(':visible') ? 'Show More' : 'Show Less')
                   .siblings().toggle(500);
         })
       );​

代码演示


0
很简单 - 选择要更改的元素并修改其文本。
$('#myButton').text('Show Less!');

0

既然您已经在点击事件中有了this,只需在其上调用.text()

.... .click(function() {
  var that = $(this);
  that.siblings().toggle(500);
  that.text("Show less!");
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接