2012-06-19 109 views
2

任何人都可以告訴我爲什麼下面的代碼似乎無法阻止鏈接做它的事情?我知道我可以使用onclick="return false",但它應該與preventDefault一起使用,對吧?我試過onclick="function(e){this.preventDefault()}"onclick="this.preventDefault()",但沒有愛。在onclick中使用preventDefault不起作用

<!doctype html> 
<html lang="en"> 
    <head> 
     <meta charset="utf-8"> 
     <title>Test</title> 
    </head> 
    <body> 
     <a href="http://www.google.com" onclick="function(e){e.preventDefault()}">Google Search</a> 
    </body> 
</html> 
+0

我會說,這取決於瀏覽器:) –

回答

13

刪除function(e){。當你把function(e){}放在那裏時,這意味着創建一個函數但不運行它。

演示:http://jsfiddle.net/DerekL/RnngR/

做這樣的:

<a href="http://www.google.com" onclick="event.preventDefault();">Google Search</a> 
+2

+1由第二 –

+0

是打我'event'標準名稱的attr參數函數? – qwertymk

+1

'event'應該可以在所有瀏覽器中運行。 –