jQuery Toggle Text?

后端 未结 20 958
日久生厌
日久生厌 2020-12-02 05:52

How to toggle HTML text of an anchor tag using jQuery? I want an anchor that when clicked the text alternates between Show Background & Show Text

20条回答
  •  攒了一身酷
    2020-12-02 06:12

    In most cases you would have more complex behavior tied to your click event. For example a link that toggles visibility of some element, in which case you would want to swap link text from "Show Details" to "Hide Details" in addition to other behavior. In that case this would be a preferred solution:

    $.fn.extend({
      toggleText: function (a, b){
        if (this.text() == a){ this.text(b); }
        else { this.text(a) }
      }
    );
    

    You could use it this way:

    $(document).on('click', '.toggle-details', function(e){
      e.preventDefault();
      //other things happening
      $(this).toggleText("Show Details", "Hide Details");
    });
    

提交回复
热议问题