开发者

Stop href link after onClick function is called

开发者 https://www.devze.com 2023-03-13 11:49 出处:网络
I have a link: <h2><a href=?p=article&aid=\'.$article->id.\'\" onclick=\"loadPage(\'articl开发者_运维知识库e\'); return false;\">.$article->title.</a></h2>

I have a link:

<h2><a href=?p=article&aid='.$article->id.'" onclick="loadPage('articl开发者_运维知识库e'); return false;">.$article->title.</a></h2>

and it calls this function:

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

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

But after my javascript has been ran the href is still active. I've used return false; on my onClick's before to prevent this but it's not working this time????


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

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

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


My favorite way to do this is to replace the href attribute. This has the advantage of preserving compatibility with non-JS clients, and not having to deal with 'stopping' the event or any such wizardry. For example:

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

    // handle the link's 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 just do unobtrusiveLinkSetup("#myLink"); in your document's ready function, or wherever else.


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;
});

Usually, if the href is still active is it likely that there was a JavaScript error.

Edit: You could also use event.preventDefault() to stop the href being followed with the click function bound in this way.

Lastly, the href does seem very well formed (missing an opening quote). Is that a typo?

0

精彩评论

暂无评论...
验证码 换一张
取 消