1. 程式人生 > >關於 href="javascript:;" 到底做了什麼

關於 href="javascript:;" 到底做了什麼

這幾天正在仿寫一個網站demo,有些細節地方想不明白就查看了網站碼源學習學習,發現自己的<a>標籤與原始碼諸多不同,雖然之前就看過很多的網站的程式碼都有這個<a href="javascript:;"></a>或這個<a href="javascript:void(0);></a>",但還是產生了疑問:

1.這種寫法的作用是什麼?

2.為什麼這樣寫?

於是隨手Google之,排名第一的是張鑫旭大神的一篇文章,第二個就是在stackoverflow上的問答。

由於張大神的這篇文章也是提出了自己的一些疑問而解釋的較少,故在這裡就不細說了。

接下來我就來看看stackoverflow上關於這個問題的高票回答。

An <a>element is invalid HTML unless it has either an href or name attribute.

If you want it to render correctly as a link (ie underlined, hand pointer, etc), then it will only do so if it has a href attribute.

Code like this is therefore sometimes used as a way of making a link, but without having to provide an actual URL in the href attribute. The developer obviously wanted the link itself not to do anything, and this was the easiest way he knew.

He probably has some javascript event code elsewhere which is triggered when the link is clicked, and that will be what he wants to actually happen, but he wants it to look like a normal <a>tag link.

Some developers usehref='#'for the same purpose, but this causes the browser to jump to the top of the page, which may not be wanted. And he couldn't simply leave the href blank, because href=''

is a link back to the current page (ie it causes a page refresh).

There are ways around these things. Using an empty bit of Javascript code in the href is one of them, and although it isn't the best solution, it does work.

看完之後真的是豁然開朗,故寫此文以敬之。

現在我就來總結一下這位名叫Spudley的大神(是真的大神,被他的主頁震驚了)的回答要點:

1.首先<a>標籤要想起作用就必須有個name屬性或是href屬性,這是前提;

2.其次<a>標籤若想有類似連結的效果,比如下劃線或者是手狀的滑鼠等,就需要有href屬性;

3.有的人會使用href="#"來實現相同的目的,但是#會使瀏覽器跳轉到頁面頂部;若使用href=''的話會重新重新整理頁面,顯然也是不必要的。

4.在href中使用一個空的Javascript程式碼是其中的一個解決方法,雖然它不是最好的解決方案,但它可以工作。

真的是遠離某度保性命,常用google漲姿勢呀。