Help me understand [removed]void(null)

前端 未结 4 1543
旧时难觅i
旧时难觅i 2021-02-19 11:15

can someone please help me with this javascript:void(null) I found it used in link buttons as follows



        
4条回答
  •  梦如初夏
    2021-02-19 11:39

    void is a JavaScript operator but is sometimes mistaken for a function because of the common use of brackets that follow it. The intended purpose of void is to evaluate an expression without returning a value. Therefore, any expression at all can be voided, it doesn't have to be null and quite often you see void(0) or less frequently, void 0.

    When you use javascript: in a href attribute, the expression following will be evaluated and its result will be returned. This can be seen by entering the following into your browser address box:

    javascript:prompt("test");
    

    Type anything into the box that appears and press enter/click ok. You will notice that the page will disappear and whatever you typed will appear. Now watch what happens if we add void 0;:

    javascript:prompt("test"); void 0;
    

    After clicking OK in the prompt, nothing happens. That's void 0's handywork, it returns undefined and so the browser does nothing about it. This applies to href in links too (feel free to try it). The whole thing could even just be written as javascript:void prompt("test");.

    As others have mentioned, it's best to use return false; from an event handler rather than using void in the href. In fact, it's recommended not to use javascript: in the href attribute at all.

提交回复
热议问题