简体   繁体   中英

How to preventDefault and disable a href

On first click my button click function works, but upon clicking again it refreshes the page click the unbind isn't recognized. I need to prevent any default click event as well as disable the button after click.

<a href="" class="red-btn2">Save this Property</a>

$(".red-btn2").click(function(event){
  event.preventDefault();
  $(this).unbind('click');
  $(this).css({
    'background-color':'#666666',
    'text-align':'center'
  });
  $(this).text("Added to Favorites");
});

If you need the rest of the handler to run only once, but preventDefault() always, you can separate them into multiple handlers.

Then, one of them can be removed after its first use (using jQuery's .one() will cover that for you), still leaving the preventDefault() in use:

$('.red-btn2')
    .click(function (event) {
        event.preventDefault();
    })
    .one('click', function () {
      $(this).css({
        'background-color':'#666666',
        'text-align':'center'
      });
      $(this).text("Added to Favorites");
    });

As you have it, the event.preventDefault() is being removed as well by .unbind('click') , so no functions are left on the element to call it for the 2nd click.

When you unbind the handler, the button will function as normal on any subsequent click, and initiate a navigation. So you better really set the disabled property:

 $(".red-btn2").click(function(event){ event.preventDefault(); if ($(this).prop('disabled')) return; // <--- $(this).prop('disabled', true); // <---- $(this).css({ 'background-color':'#666666', 'text-align':'center' }); $(this).text("Added to Favorites"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="" class="red-btn2">Save this Property</a> 

Note that event.preventDefault() actually works. It was only on the second click you had issues, because the link was still clickable, but your function was detached from it, so you had no control over that second click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM