预防href =“#”链接改变URL散列 [英] Prevent href="#" link from changing the URL hash

查看:128
本文介绍了预防href =“#”链接改变URL散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站已经利用网址中的哈希值,我不希望它改变。当我使用Zurb基金会并使用 href =#作为菜单项时,点击它将删除以前的散列值。



如何覆盖此行为?



更新:我认为留在元素中更好,因为当我更改它时,它会更改绑定到该HTML元素的样式。


$ b 谢谢。

渐进式增强和 Unobtrusive JavaScript



您应该(几乎)永远不会有 HREF = #。这是一个链接到一个未定义的锚点(这将是页面的顶部)。使用它的人通常会这样做,因为他们想把JavaScript从它身上吊起来。



如果你要有链接,那么它应该指向某个有用的地方。通常,这将是另一个使用服务器端技术的页面,以获得与JavaScript相同的效果(虽然速度较慢)。您可以阻止链接的正常行为。



例如:

 < a href =/ foo / barclass =whatever> Foo:Bar< / a> 

使用脚本:

  addEventListener('click',function(ev){
if(ev.target.classList.contains('whatever')){
ev.preventDefault();
loadWithAjax(ev.target.href);
}
});

如果JavaScript做了某些功能不能在链接中表达的功能,那么您不应该首先使用链接。使用<按钮> ,并认真考虑使用JavaScript / DOM而不是HTML将其添加到文档中。

(注意:很多人都希望支持不承认 classList addEventListener 检查浏览器支持并找到兼容性例程作为读者的练习。使用YUI,jQuery或类似的方法是处理兼容性的一种方法。 p>

I have a site that already takes advantage of the hash in the URL and I don't want it changed. When I use Zurb Foundation and use href="#" for the menu item, clicking on it removes the previous hash value.

How can I override this behavior?

Update: I think that it's better to stay with element because when I change it, it changes the styling that is bound to that HTML element. I always prefer when using with a design framework to stay with the default conventions and not mass with overriding css attributes.

thanks.

解决方案

Please read up on Progressive Enhancement and Unobtrusive JavaScript.

You should (almost) never have href="#". It is a link to an undefined anchor (which will be the top of the page). People who use it normally do so because they want to dangle JavaScript off it.

If you are going to have a link, then it should point to somewhere useful. Typically this will be another page that uses server side technology to get the same effect (albeit less quickly) as the JavaScript would give. You can then prevent the normal behaviour of the link.

For example:

<a href="/foo/bar" class="whatever">Foo: Bar</a>

With the script:

addEventListener('click', function (ev) {
    if (ev.target.classList.contains('whatever')) {
        ev.preventDefault();
        loadWithAjax(ev.target.href);
    }   
});

If the JavaScript does something that can't have equivalent functionality expressed in a link, then you shouldn't be using a link in the first place. Use a <button>, and seriously consider adding it to the document using JavaScript/DOM instead of HTML.

(NB: Quite a lot of people want to support older browsers which don't recognise classList or addEventListener checking browser support and finding compatibility routines is left as an exercise for the reader. Using YUI, jQuery or similar is one approach for dealing with compatibility.)

这篇关于预防href =“#”链接改变URL散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆