如何在点击事件中正确更改/更新按钮的文本和字体图标?



$(".btn-warning").click(function() {
      $(this).toggle(function() {
          $('.btn-warning').text("Remove Filter <i class='fa fa-filter'></i>");
      }, function() {
          $('.btn-warning').text("Apply Filter <i class='fa fa-remove'></i>");
      });
    });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<button type="button" class="btn btn-warning">Apply Filter <i class="fa fa-filter"></i></button>

最佳答案

干得好。



$(".btn-warning").click(function() {
    var $btn = $(this);
    if ($btn.hasClass('x-on')) {
        $btn.removeClass('x-on').html("Apply Filter <i class='fa fa-filter'></i>");
    } else {
        $btn.addClass('x-on').html("Remove Filter <i class='fa fa-remove'></i>");
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<button type="button" class="btn btn-warning">Apply Filter <i class="fa fa-filter"></i></button>

10-04 22:06