href="javascript:void(0);" considered harmful

aragorn_177發表於2008-07-13

有時候使用<a>標記僅僅是用來掛載click事件,我們常常這樣寫:

  • <a href="javascript:void(0);" onclick="doSomething();">click</a>

  • <a href="javascript:void 0;" onclick="doSomething();">click</a>

  • <a href="javascript:;" onclick="doSomething();">click</a>

  • <a href="javascript:void doSomething();">click</a>

這些寫法利用javascript“協議void運算子來告訴瀏覽器這個連結哪裡都不去,從而取消<a>作為超級連結的作用。不過會帶來一些問題,尤其是用於開啟popup windows時:

  • 不能使用右鍵選單中的open in new window

  • 不能把連結地址加入收藏夾

  • 狀態列會顯示出終端使用者搞不懂的程式碼,他們會認為出錯了

  • 一旦指令碼下載不完整或瀏覽器僅用了JavaScript,網頁會非常sb

更為嚴重的是,在IE中會導致一些你永遠也猜不出原因的古怪問題。例如IE6中,用這種方法掛載的事件處理函式中改變imgsrc屬性,瀏覽器不會顯示圖片,必須在右鍵選單中點show picture才能顯示

XHTML:

<a href="#" onclick="aFunction();return false;">

A Link

</a>

The return false (that must appear after the last function call) informs the browser that the action of returning a reference to a URL, should not evaluate. Instead it should return false, including internal links, and therefore it does nothing.

相關文章