Jquery:在禁用按钮单击/悬停时显示消息

时间:2016-02-19 08:25:58

标签: javascript jquery

如果用户点击禁用按钮,我想显示信息消息。我的代码制作了它,但信息消息只出现了很短的时间,然后上一个成功消息继续显示。如何更改代码以强制信息消息停止并且不会消失?

  

更新:我在代码中进行了微小的更改,现在它禁用了按钮   刚刚第一次点击并显示成功消息(之前禁用我应该再次点击)但我想如果用户偶尔再次按下禁用按钮他将收到信息消息。如何使它成为可能?

$(document).ready(function() {
  $('#s1-btn').click(function(e) {
    e.preventDefault();
    $(this).prop('disabled', true)
    $.post(
      "/run-key-gen-process/",
      onAjaxSuccess
    );

    function onAjaxSuccess(data) {
      if (data == "Key was succesfully generated an tested!") {
        $("#jmessage").addClass("alert alert-success")
          .text(data).fadeOut(6000);
      }
      $('#s1-btn').click(function() {
        $("#jmessage").removeClass("alert alert-success").addClass("alert alert-info")
          .text("Button is disabled since you already generated and tested the key");
      });
    };
  });
})    

template.html

<div class="row" id="div-st1">
  <div class="col-md-3 ">
    <button type="submit" method="POST" id="s1-btn" class="form-inline btn btn-info pull-left">Generate</button>
  </div>
  <div class="col-md-6 " id="jmessage" role="alert"></div>
</div>

2 个答案:

答案 0 :(得分:1)

我想问题是在成功回调中再次在同一个按钮上重新绑定click事件,你可以改为:

    $(document).ready(function() {
      $('#s1-btn').click(function(e) {
        e.preventDefault();
        var $this = $(this);
        var isDisabled = $this.is('disabled');
        if (isDisabled) {
          $("#jmessage").removeClass("alert alert-success").addClass("alert alert-info")
            .text("Button is disabled since you already generated and tested the key");
          return !isDisabled;
        } else {
          $this.prop('disabled', !isDisabled); // <-----disable it here.
          $.post(
            "/run-key-gen-process/",
            onAjaxSuccess
          );
        }

        function onAjaxSuccess(data) {
          if (data == "Key was succesfully generated an tested!") {
            $this.prop('disabled', !!data);// <-----enable it here.
            $("#jmessage").removeClass("alert alert-info").addClass("alert alert-success")
              .text(data).fadeOut(6000);
          }
        };
      });
    })

答案 1 :(得分:0)

我已经像这样修改了我的代码,现在它做了应有的事情。如果用户单击按钮,则会运行密钥生成,显示成功消息并禁用按钮。如果用户单击/移动鼠标,则显示禁用按钮信息消息。

$(document).ready(function() {
  $('#s1-btn').click(function(e) {
    e.preventDefault();
    $(this).prop('disabled', true);
    $("#div-st1").mouseenter(function() {
      $("#jmessage").removeClass("alert alert-success").addClass("alert alert-info")
        .text("Button is disabled since you already generated and tested the key");
    });
    $.post(
      "/run-key-gen-process/",
      onAjaxSuccess
    );

    function onAjaxSuccess(data) {
      if (data == "Key was succesfully generated an tested!") {
        $("#jmessage").addClass("alert alert-success")
          .text(data);
      }
    };
  });
});