Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

hyperlink - jQuery disable a link

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 a click on it using jquery which triggers some stuff, then re-enabling that link so that if it's clicked again it works as default.

Thanks. Dave

UPDATE Here's the code. What it needs to do after the .expanded class has been applied is to re-enable the disabled link.

$('ul li').click(function(e) {
    e.preventDefault();
    $('ul').addClass('expanded');
    $('ul.expanded').fadeIn(300);
    //return false;
});
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$('#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);
    } 
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...