I want a link to either execute a JavaScript function (if JavaScript is available) or enter the URL in the href attribute if it's not.

<a href="http://www.example.com" onclick="example(); return false;">

In this example, I'd want to execute example() and not enter the link if JavaScript is available or go to http://www.example.com if JavaScript is unavailable.

While this works in almost every browser I've tried it with, in IE 7, regardless of if JavaScript is active or not, it just follows the link. What can I do to prevent this?

有帮助吗?

解决方案

This may be what you are looking for

event.returnValue = false;

Retrieved from here: event.preventDefault() function not working in IE

其他提示

You have to use preventDefault() on the event object to prevent the default action (that is, navigating to the link's URL).

Because the implementation differes a little bit in browsers, you should write a separate function for doing this and call it in your event handler:

function preventDefault(event) {
        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false;
        }
}

Also, be sure to return false in your event handler.

If you're using any JavaScript library, then this functionality is very likely to already be present.

Separate your javascript from HTML :)

<a href="http://www.example.com" id='uniq-link'>
$(function () {
    $("#uniq-link").on("click", example);
});

If Javascript is unavailable - all will be ok :)

Try this:

<a href="http://www.example.com" onclick="example(); event.returnValue=false; return false;">
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top