How to trigger a click event on disabled elements

后端 未结 5 901
难免孤独
难免孤独 2021-01-11 23:18

I have a disabled button, which is enabled after checking \"I accept terms and conditions\" checkbox. The problem is that I wanted to trigger an alert, if a user cli

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-11 23:52

    If you use Twitter Bootstrap, they give you a class disabled that provides the styling but doesn't remove the click event. Given that, what I did was this (keep in mind also, I wanted to be sure that when the button was no longer disabled, the original click event did fire, and I didn't want to deal with unbinding, rebinding it).

    function disableButton(btn, message) {
      btn.addClass("disabled")
      if (!(message == null || message == "")) {
        btn.data("message", message)
      }
    }
    
    function enableButton(btn) {
      btn.removeClass("disabled")
    }
    
    $("#btn").click(function() {
      if (!($(this).hasClass("disabled"))) {
        // original, desired action
      } else {
        message = $(this).data("message")
        if (!(message == null || message == "")) {
          alert(message)
        }
      }
    

    })

提交回复
热议问题