Stop href link after calling onClick function

I have a link:

<h2><a href=?p=article&aid='.$article->id.'" onclick="loadPage('article'); return false;">.$article->title.</a></h2>

and he calls this function:

function loadPage(page){
    $("#content").html("Loading...");

    $.post("page.php", {p: page}, function(data){
        $("#content").html(data);   
    });
}

But after running javascript href is still active. I used return false; to my onClick before to prevent this, but it doesn’t work this time ????

+3
source share
3 answers

It looks like your script has an error and does not reach the return block. If you add try catch, it will ignore errors in the script.

function loadPage(page){
try{
    $("#content").html("Loading...");

    $.post("page.php", {p: page}, function(data){
        $("#content").html(data);   
    });
} catch(err){}
}
+1
source

You might be better off using jQuery to bind the click event to your function, as the logic is better separated.

$('h2 a').click(function(event) {
    $("#content").html("Loading...");

    $.post("page.php", {p: page}, function(data){
        $("#content").html(data);   
    });

    return false;
});

Normally, if the parameter hrefis still active, a JavaScript error probably occurred.

: event.preventDefault(), href, .

, href ( ). ?

+1

My favorite way to do this is to replace the href attribute. The advantage of this is to maintain compatibility with non-JS clients and not have to deal with the “stopping” of the event or any such magic. For instance:

function unobtrusiveLinkSetup(link) {
    // replace the about link href
    J(link).attr('jshref', J(link).attr('href'));
    J(link).removeAttr('href');

    // handle the link action
    J(link).click(function(index) {
            J(this).stop();
            // make a request in the background
            J.get(J(this).attr('jshref'), function(result) {
                // whatever you need to do with the link..
            });
    });
}

Then you can simply do it unobtrusiveLinkSetup("#myLink");in your finished documentation or anywhere.

+1
source

All Articles