2014-08-28 25 views
0

我有JavaScript,它使用'href =「#」'來單擊時調用一個函數。問題是,當我在Chrome上運行它時,我需要2次後退才能返回到引用頁面,但在Opera上,我只需要1次後退按鈕。使用'href =「#」'需要2在某些瀏覽器中後退

我讀的細節有關使用 'HREF = 「#」' 在這裏: What is href="#" and why is it used?

這裏是我的測試代碼:

<p> 
    <script type="text/javascript"> 
     function testOnClick(){ 
      document.write("onClick() support was detected!<br>"); 
     } 
    </script> 
</p> 

Clicking on the link should clear the screen and display progress text<br /> 
<a onclick="testOnClick();" href="#!"> 
    Click here to test onClick 
</a> 
+0

與破折號鏈接找到的信息,創造了歷史新的條目。第一次後推可將您帶到同一頁面,而無需散列,第二次帶您前往頁面。 – keune 2014-08-28 17:06:52

+0

爲什麼指定'href'呢?你真的需要這種行爲嗎?你可以設置''的樣式,使它具有'cursor:pointer'和'text-decoration:underline'。 – canon 2014-08-28 17:17:22

回答

2

您可能需要使用event.preventDefault();

function testOnClick(event) { 
    event.preventDefault(); 
    document.write("onClick() support was detected!<br>"); 
} 

它阻止您的導航器導航到#鏈接,因此不得不按回去。

0

您還可以通過使用不同的元素並使其看起來像鏈接來獲得類似的功能。例如,如果您不是將用戶導航到頁面的不同部分或新頁面,則可能應該使用<a>標籤。

這裏有一個搗鼓我的意思:http://jsfiddle.net/2ph2d2gd/

使用情況下這將打開一個模式,或者做一些其他的行動,並不一定在任何地方對用戶進行導航。我不知道你的具體情況,所以你可能會也可能不想要使用這樣的東西。

注:我用alert而不是document.write,因爲jsfiddle不允許後者。

HTML:

Clicking on the link should clear the screen and display progress text<br /> 
<span class="link" onclick="testOnClick();"> 
    Click here to test onClick 
</span> 

CSS:

.link{ 
    text-decoration:underline; 
    color:blue; 
    cursor:pointer; 
} 

的Javascript:

function testOnClick(){ 
    alert("onClick() support was detected!"); 
} 
0

我有很好的效果留下空白的href在這種情況下。它不會在URL的末尾重新加載帶「#」的頁面,並且事件仍然會觸發。

我不確定JS的onclick效果如何,但可以用jQuery替換。

<script type="text/javascript"> 
    $(function() { 
     $("#link").on("click", function() { 
      alert("click"); 
     }); 
    }); 
</script> 
<a id="link" href=""> 
    Click here to test onClick 
</a> 
0

如果使用href="#",確保onclick總是包含return false;最後,任何調用的函數都不會拋出錯誤,並且如果您將函數動態添加到onclick屬性中,請確保不會拋出錯誤,並返回false

OR

使用href="javascript:void(0)"

更多關於爲何能在this question

相關問題