AddClass/RemoveClass Issues

前端 未结 3 1224
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-26 11:27

On the click of button with class A, replace class A with class B. On the click of button with class B I need to perform an action.

It\'s applying/removing the class cor

相关标签:
3条回答
  • 2021-01-26 11:46

    Use event delegation. Added semicolons, too:

    $(document).on('click', ".changebut", function () {
       $("input[type=text]").fadeOut("fast", function () {
          $(".changebut").animate({
               width: "100%"
          }, 200).val("Submit again").removeClass("changebut").addClass("submitbut");
       });
    });
    $(document).on('click', ".submitbut", function () {
       alert('it worked!');
    });
    
    0 讨论(0)
  • 2021-01-26 11:56

    The easiest solution if to use event delegation instead of direct binding :

    $(document).on('click', '.changebut', function () {
        $("input[type=text]").fadeOut("fast", function () {
            $(".changebut").animate({
                 width: "100%"
             }, 200).val("Submit again").removeClass("changebut").addClass("submitbut")
        });
    })
    
    $(document).on('click', '.submitbut', function () {
        alert('it worked!')
    })
    

    The best solution is to bind the click event directly and check for the current class :

    $(".changebut").on('click', function () {
        if($(this).is('.changebut')){
            $("input[type=text]").fadeOut("fast", function () {
                $(".changebut").animate({
                    width: "100%"
                }, 200).val("Submit again").removeClass("changebut").addClass("submitbut")
            });
        }else{
            alert('i have an other class');
        }
    })
    
    0 讨论(0)
  • 2021-01-26 12:06

    Use a single event binding that handles both actions.

    $(".changebut,.submitbut").click(function () {
       if ($(this).is(".changebut")) {
           $("input[type=text]").fadeOut("fast", function () {
               $(".changebut").animate({
                   width: "100%"
               }, 200).val("Submit again").removeClass("changebut").addClass("submitbut")
           });
        } else {
            alert("It worked!");
        }
    });
    
    0 讨论(0)
提交回复
热议问题