What does “[removed]void(0)” mean?

前端 未结 14 1347
说谎
说谎 2020-11-21 15:23
login

I\'ve seen such hrefs many times, but I don\'t know what exactly

相关标签:
14条回答
  • 2020-11-21 15:56

    There is a huge difference in the behaviour of # vs javascript:void(0);.

    # scrolls you to the top of the page but javascript:void(0); does not.

    This is very important if you are coding dynamic pages because the user does not want to go back to the top when they click a link on the page.

    0 讨论(0)
  • 2020-11-21 15:56

    The void operator evaluates the given expression and then returns undefined. It avoids refreshing the page.

    0 讨论(0)
  • 2020-11-21 15:58

    It means it’ll do nothing. It’s an attempt to have the link not ‘navigate’ anywhere. But it’s not the right way.

    You should actually just return false in the onclick event, like so:

    <a href="#" onclick="return false;">hello</a>
    

    Typically it’s used if the link is doing some ‘JavaScript-y’ thing. Like posting an AJAX form, or swapping an image, or whatever. In that case you just make whatever function is being called return false.

    To make your website completely awesome, however, generally you’ll include a link that does the same action, if the person browsing it chooses not to run JavaScript.

    <a href="backup_page_displaying_image.aspx"
       onclick="return coolImageDisplayFunction();">hello</a>
    
    0 讨论(0)
  • 2020-11-21 16:00

    A link must have an href target to be specified to enable it to be a usable display object.

    Most browsers will not parse advanced JavaScript in the href of an <a> element, for example:

    <a href="javascript:var el = document.getElementById('foo');">Get element</a>
    

    Because the href tag in most browsers does not allow whitespace or will convert whitespace to %20 (the HEX code for space), the JavaScript interpreter will run into multiple errors.

    So if you want to use an <a> element's href to execute inline JavaScript, you must specify a valid value for href first that isn't too complex (doesn't contain whitespace), and then provide the JavaScript in an event attribute tag like onClick, onMouseOver, onMouseOut, etc.

    The typical answer is to do something like this:

    <a href="#" onclick="var el = document.getElementById('foo');">Get element</a>
    

    This works fine but it makes the page scroll to the top because the # in the href tells the browser to do this.

    Placing a # in the <a> element's href specifies the root anchor, which is by default the top of the page, but you can specify a different location by specifying the name attribute inside an <a> element.

    <a name="middleOfPage"></a>
    

    You can then change your <a> element's href to jump to middleOfPage and execute the JavaScript in the onClick event:

    <a href="#middleOfPage" onclick="var el = document.getElementById('foo');">Get element</a>
    

    There will be many times where you do not want that link jumping around, so you can do two things:

    <a href="#thisLinkName" name="thisLinkCame" onclick="var elem = document.getElementById('foo');">Get element</a>
    

    Now it will go nowhere when clicked, but it could cause the page to re-centre itself from its current viewport.

    The best way to use in-line javascript using an <a> element's href, but without having to do any of the above is JavaScript:void(0);:

    <a href="javascript:void(0);" onclick="var el = document.getElementById('foo');">Get element</a>
    

    This tells the browser no to go anywhere, but instead execute the JavaScript:void(0); function in the href because it contains no whitespace, and will not be parsed as a URL. It will instead be run by the compiler.

    void is a keyword which, when supplied with a parameter of 0 returns undefined, which does not use any more resources to handle a return value that would occur without specifying the 0 (it is more memory-management/performance friendly).

    The next thing that happens is the onClick gets executed. The page does not move, nothing happens display-wise.

    0 讨论(0)
  • 2020-11-21 16:01

    In addition to the technical answer, javascript:void means the author is Doing It Wrong.

    There is no good reason to use a javascript: pseudo-URL(*). In practice it will cause confusion or errors should anyone try things like ‘bookmark link’, ‘open link in a new tab’, and so on. This happens quite a lot now people have got used to middle-click-for-new-tab: it looks like a link, you want to read it in a new tab, but it turns out to be not a real link at all, and gives unwanted results like a blank page or a JS error when middle-clicked.

    <a href="#"> is a common alternative which might arguably be less bad. However you must remember to return false from your onclick event handler to prevent the link being followed and scrolling up to the top of the page.

    In some cases there may be an actual useful place to point the link to. For example if you have a control you can click on that opens up a previously-hidden <div id="foo">, it makes some sense to use <a href="#foo"> to link to it. Or if there is a non-JavaScript way of doing the same thing (for example, ‘thispage.php?show=foo’ that sets foo visible to begin with), you can link to that.

    Otherwise, if a link points only to some script, it is not really a link and should not be marked up as such. The usual approach would be to add the onclick to a <span>, <div>, or an <a> without an href and style it in some way to make it clear you can click on it. This is what StackOverflow [did at the time of writing; now it uses href="#"].

    The disadvantage of this is that you lose keyboard control, since you can't tab onto a span/div/bare-a or activate it with space. Whether this is actually a disadvantage depends on what sort of action the element is intended to take. You can, with some effort, attempt to mimic the keyboard interactability by adding a tabIndex to the element, and listening for a Space keypress. But it's never going to 100% reproduce the real browser behaviour, not least because different browsers can respond to the keyboard differently (not to mention non-visual browsers).

    If you really want an element that isn't a link but which can be activated as normal by mouse or keyboard, what you want is a <button type="button"> (or <input type="button"> is just as good, for simple textual contents). You can always use CSS to restyle it so it looks more like a link than a button, if you want. But since it behaves like a button, that's how really you should mark it up.

    (*: in site authoring, anyway. Obviously they are useful for bookmarklets. javascript: pseudo-URLs are a conceptual bizarreness: a locator that doesn't point to a location, but instead calls active code inside the current location. They have caused massive security problems for both browsers and webapps, and should never have been invented by Netscape.)

    0 讨论(0)
  • 2020-11-21 16:05

    It is a very popular method of adding JavaScript functions to HTML links.
    For example: the [Print] links that you see on many webpages are written like this:

    <a href="javascript:void(0)" onclick="callPrintFunction()">Print</a>
    

    Why do we need href while onclick alone can get the job done? Because when users hover over the text 'Print' when there's no href, the cursor will change to a caret (ꕯ) instead of a pointer (👆). Only having href on an a tag validates it as a hyperlink.

    An alternative to href="javascript:void(0);", is the use of href="#". This alternative doesn't require JavaScript to be turned on in the user's browser, so it is more compatible.

    0 讨论(0)
提交回复
热议问题