如何防止锚标签上的默认值? [英] How to preventDefault on anchor tags?

查看:27
本文介绍了如何防止锚标签上的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个锚标记,例如

Let's say I have an anchor tag such as

<a href="#" ng-click="do()">Click</a>

如何防止浏览器导航到 AngularJS 中的 # ?

How can I prevent the browser from navigating to # in AngularJS ?

推荐答案

UPDATE:从那以后,我改变了对这个解决方案的看法.经过更多的开发和时间花在这上面的工作,我相信这个问题的更好解决方案是执行以下操作:

UPDATE: I've since changed my mind on this solution. After more development and time spent working on this, I believe a better solution to this problem is to do the following:

<a ng-click="myFunction()">Click Here</a>

然后更新您的 css 以增加一条规则:

And then update your css to have an extra rule:

a[ng-click]{
    cursor: pointer;
}

它更简单,提供完全相同的功能,而且效率更高.希望这可能对将来查找此解决方案的其他人有所帮助.

Its much more simple and provides the exact same functionality and is much more efficient. Hope that might be helpful to anyone else looking up this solution in the future.

以下是我之前的解决方案,我将其留在这里仅用于遗留目的:

如果您经常遇到此问题,可解决此问题的简单指令如下:

If you are having this problem a lot, a simple directive that would fix this issue is the following:

app.directive('a', function() {
    return {
        restrict: 'E',
        link: function(scope, elem, attrs) {
            if(attrs.ngClick || attrs.href === '' || attrs.href === '#'){
                elem.on('click', function(e){
                    e.preventDefault();
                });
            }
        }
   };
});

它检查所有的锚标签()以查看它们的href属性是否为空字符串("") 或散列 ('#') 或存在 ng-click 分配.如果它发现这些条件中的任何一个,它就会捕获该事件并阻止默认行为.

It checks all anchor tags (<a></a>) to see if their href attribute is either an empty string ("") or a hash ('#') or there is an ng-click assignment. If it finds any of these conditions, it catches the event and prevents the default behavior.

唯一的缺点是它为所有锚标记运行此指令.因此,如果页面上有很多锚标记,而您只想阻止其中一小部分的默认行为,那么该指令的效率就不是很高.但是,我几乎总是希望 preventDefault,所以我在我的 AngularJS 应用程序中到处使用这个指令.

The only down side is that it runs this directive for all anchor tags. So if you have a lot of anchor tags on the page and you only want to prevent the default behavior for a small number of them, then this directive isn't very efficient. However, I almost always want to preventDefault, so I use this directive all over in my AngularJS apps.

这篇关于如何防止锚标签上的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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