2014-08-28 65 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