如何美元锚标签p $ pventDefault? [英] How to preventDefault on anchor tags?

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

问题描述

让我们说我有一个锚标记,如

Let's say I have an anchor tag such as

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

我如何prevent从导航到#浏览器的 AngularJS

推荐答案

更新:因为我已经改变了我的脑海里对这个解决方案。经过发展和时间花在这方面的工作,我认为更好的解决这个问题是要做到以下几点:

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 有一个额外的规则:

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.

以下是我的previous解决方案,我离开这里只是对传统用途:

如果您有这个问题有很多,简单的指令,将解决这个问题如下:

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();
                });
            }
        }
   };
});

这将检查所有锚标签(&LT; A&GT;&LT; / A&GT; ),看看他们的的href 属性为空字符串()或哈希('#'),或者有一个 NG-点击分配。如果发现任何这些条件,它捕获的事件和prevents的默认行为。

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.

唯一的缺点是,它运行这个指令对所有锚标签。所以,如果你在页面上大量的锚标签,而你只需要prevent为少数人的默认行为,那么这个指令是不是很有效。但是,我几乎总是想 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.

这篇关于如何美元锚标签p $ pventDefault?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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