开发者

How do I cancel the link action?

I though returning false would be enough to cancel the link action, but apparently it isn't. When I click the link in the code below I do get the 'click' message, which is expected. But I also end up at google.com, which is unexpected.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Link test</title>
    <script>
        window.addEventListener('load', function () {
            document.getElementsByTagName('a')[0].addEventListener('click', function () {
        开发者_StackOverflow社区        alert('click');
                return false;
            }, false);
        }, false);
    </script>
</head>
<body>
    <a href="http://www.google.com">google</a>
</body>
</html>

How can I make the url NOT change when clicking the link? Pure JavaScript solutions only please, no additional libraries (like jQuery). It only has to work in FireFox 3+ and Chrome.


If you don't want the url on on the anchor to change the location you can try the following

document.getElementsByTagName('a')[0].addEventListener('click', function (e) {
            alert('click');
            e=e¦¦event; 
            e.preventDefault? e.preventDefault() : e.returnValue = false; 
        }, false);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜