jQuery disable a link

前端 未结 17 1359
半阙折子戏
半阙折子戏 2020-11-22 14:45

Anyone know how to disable a link in jquery WITHOUT using return false;?

Specifically, what I\'m trying to do is disable the link of an item, performing

17条回答
  •  悲&欢浪女
    2020-11-22 15:34

    For others who came here via google like me - here's another approach:

    css:
    .disabled {
      color: grey; // ...whatever
    }
    
    jQuery:
    $('#myLink').click(function (e) {
      e.preventDefault();
      if ($(this).hasClass('disabled'))
        return false; // Do something else in here if required
      else
        window.location.href = $(this).attr('href');
    });
    
    // Elsewhere in your code
    if (disabledCondition == true)
      $('#myLink').addClass('disabled')
    else
      $('#myLink').removeClass('disabled')
    

    Remember: not only this is a css class

    class="buttonstyle"

    but also these two

    class="buttonstyle disabled"

    so you can easily add and remove further classes with jQuery. No need to touch href...

    I love jQuery! ;-)

提交回复
热议问题