【问题标题】:jQuery: Change button text on clickjQuery:单击时更改按钮文本
【发布时间】:2013-10-14 17:02:17
【问题描述】:

看到Toggling button text in jquery这个问题后,我尝试在我的情况下重新创建它,但似乎无法正常工作。

这是我所做的一个小技巧:http://jsfiddle.net/V4u5X/

$('.SeeMore2').click(function(){
    var $this = $(this);
    $this.toggleClass('SeeMore');
    if($this.hasClass('.SeeMore2')){
        $this.text('See More');         
    } else {
        $this.text('See Less');
    }
});

似乎只运行一次 if 语句。我错过了什么?

【问题讨论】:

  • 不要在hasClass的参数中添加.
  • 如果我这样做,它实际上根本不会改变文本
  • 你切换了 seeMore 类,但从不处理 seemore2

标签: jquery


【解决方案1】:
$('.SeeMore2').click(function(){
    var $this = $(this);
    $this.toggleClass('SeeMore2');
    if($this.hasClass('SeeMore2')){
        $this.text('See More');         
    } else {
        $this.text('See Less');
    }
});

应该这样做。您必须确保切换正确的类并取出“。”来自hasClass

http://jsfiddle.net/V4u5X/2/

【讨论】:

  • facepalm 我误解了 .toggleClass 的论点。我假设您会在 () 中指定一个单独的类。在我原来的版本中,它仍然有 SeeMore2 类,现在我查看它。感谢您的帮助!
  • 不适用于包含多个条目且具有多个相同按钮实例的存档。 @Scherf
【解决方案2】:

试试这个, 这个 javascript 代码一直更改文本以单击按钮。http://jsfiddle.net/V4u5X/2/

html代码

<button class="SeeMore2">See More</button>

javascript

$('.SeeMore2').click(function(){
        var $this = $(this);
        $this.toggleClass('SeeMore2');
        if($this.hasClass('SeeMore2')){
            $this.text('See More');         
        } else {
            $this.text('See Less');
        }
    });

【讨论】:

    【解决方案3】:

    它的工作短代码

    $('.SeeMore2').click(function(){ var $this = $(this).toggleClass('SeeMore2'); if($(this).hasClass('SeeMore2')) { $(this).text('See More');
    } else { $(this).text('See Less'); } });

    【讨论】:

      【解决方案4】:

      在 HTML 中:

      <button type="button" id="AddButton" onclick="AddButtonClick()" class="btn btn-success btn-block ">Add</button> 
      

      在 Jquery 中编写这个函数:

          function AddButtonClick(){ 
            //change text from add to Update
            $("#AddButton").text('Update');
          }
      

      【讨论】:

        【解决方案5】:

        这应该适合你:

            $('.SeeMore2').click(function(){
                var $this = $(this);
                $this.toggleClass('SeeMore2');
                if($this.hasClass('SeeMore2')){
                    $this.text('See More');         
                } else {
                    $this.text('See Less');
                }
        });
        

        【讨论】:

          【解决方案6】:

          使用:

          $("button").click(function(){
            $(this).html("the new text");
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-10-15
            • 2011-06-18
            • 1970-01-01
            • 2016-02-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-01-20
            相关资源
            最近更新 更多