jQuery disable a link

前端 未结 17 1193
半阙折子戏
半阙折子戏 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:37

    $('#myLink').click(function(e) {
        e.preventDefault();
        //do other stuff when a click happens
    });
    

    That will prevent the default behaviour of a hyperlink, which is to visit the specified href.

    From the jQuery tutorial:

    For click and most other events, you can prevent the default behaviour - here, following the link to jquery.com - by calling event.preventDefault() in the event handler

    If you want to preventDefault() only if a certain condition is fulfilled (something is hidden for instance), you could test the visibility of your ul with the class expanded. If it is visible (i.e. not hidden) the link should fire as normal, as the if statement will not be entered, and thus the default behaviour will not be prevented:

    $('ul li').click(function(e) {
        if($('ul.expanded').is(':hidden')) {
            e.preventDefault();
            $('ul').addClass('expanded');
            $('ul.expanded').fadeIn(300);
        } 
    });
    

提交回复
热议问题