开发者

Why is javascript:void(0) considered harmful?

Can anybody tell me or point me to some resource which explains why using javascript:void(0) in hyperlinks开发者_C百科 is harmful (especially in Internet Explorer 6)?


Use of the javascript: keyword in a link isn't recommended anyway. I've only managed to find one article on why it might be harmful:

a href=”javascript:void(0);” — avoid the void

But the general consensus shows that you shouldn't use it because it might confuse browsers without javascript support, for some of those browsers it could be parsed as an invalid link.

Instead, you should provide a link to a page either working around the functionality that would be provided by javascript or displaying a message about the site requiring javascript to work correctly. On the same link, return false; from your event, like so:

<a href="noscript.html" onclick="doSomething(); return false;">I'm a link</a>

Or alternatively, use return false; or preventDefault() and returnValue in your javascript code:

element.onclick = function ()
{
    /*
        // return false is better for most situations (see bobince's comment)
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    */

    doSomething();

    return false;
}


Click on <a href="javascript:void(0)" /> triggers event "beforeunload" in object "window" в IE (I have tested in IE10), but click on <a href="#" /> doesn't.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜