首页 > 解决方案 > jQuery:文本并在单击时禁用它

问题描述

我想显示按钮的文本并在单击后将其禁用。

<button id="btnResendVerificationEmail" class="btn btn-success">click text</button>

<script type="text/javascript">
  jQuery('#btnResendVerificationEmail').click(function() {
    jQuery.post('clientarea.php', {
      'token': '{$token}',
      'action': 'resendVerificationEmail'
    }).done(function(data) {
      jQuery('#btnResendVerificationEmail').prop('disabled', true).text('done text');
    });
  });
</script>

标签: javascriptjquery

解决方案


考虑使用jQuery.ajax()可以使用beforeSend回调的地方。这允许您在 HTTP Post 之前修改 Button。success然后你可以在回调中再次修改它。

jQuery(function($) {

  var int;
  var c = 0;

  function showLoading(obj) {
    int = setInterval(function() {
      var t = "Load";
      switch (c % 3) {
        case 0:
          t += "...";
          break;
        case 1:
          t += "..";
          break;
        case 2:
          t += ".";
          break;
      }
      c++;
      obj.html(t);
    }, 200);
  }

  $('#btnResendVerificationEmail').click(function() {
    $.ajax({
      url: "https://reqres.in/api/users",
      data: {
        token: "token-1234",
        action: "resendVerficiationEmail"
      },
      method: "POST",
      beforeSend: function() {
        $('#btnResendVerificationEmail').prop("disabled", true);
        showLoading($('#btnResendVerificationEmail'));
      },
      success: function(data) {
        clearInterval(int);
        $('#btnResendVerificationEmail').html("Done");
        console.log(data);
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnResendVerificationEmail" class="btn btn-success">Send</button>

阅读更多:https ://api.jquery.com/jquery.ajax/


推荐阅读