拦截点击链接

时间:2015-11-27 10:05:42

标签: javascript angularjs

在Angular应用程序中,是否有可能以某种方式拦截链接上的所有点击(或特定控制器视图范围内的所有链接)?例如,如果我想截取链接上的所有点击,并阻止点击youtube链接,可以这样做吗?

理想情况下,我不想添加任何自定义属性或使用自定义元素来实现此目的,即链接应该看起来像常规HTML链接。

3 个答案:

答案 0 :(得分:2)

使用angular,您可以为元素<a>添加指令,并在click上添加一个侦听器

app.directive('a', function() {
    return {
        restrict: 'E', // only Elements (<a>),
        link: function(scope, elm, attr) {
            // every time you click on the link
            elm.on('click', function($event) {
                console.log('event')
                $event.preventDefault()
                return false
            })
        }
    }
})

和田田!

现在,如果你想阻止一些URL,你可以通过attr.href访问链接功能中的href元素,所以你会这样做:

app.directive('a', function() {
    return {
        restrict: 'E', // only Elements (<a>),
        link: function(scope, elm, attr) {
            // every time you click on the link
            elm.on('click', function($event) {
                // only some URLs
                if(attr.href.match(/youtube\.com/)) {
                    $event.preventDefault()
                    return false
                }
            })
        }
    }
})

答案 1 :(得分:0)

我基于jQuery为此做了一个示例。

&#13;
&#13;
// Contents, Controls or document ready 
$(document).ready(function(){
  $('.block').find('a').each ( function(){
      $(this).click(function(){
      	  console.log('custom-action');
          return false;
      });
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="block">
    <div><a href="http://naver.com" target="_blank">OK</a></div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这个例子是用 Vanilla JS 构建的,它会拦截所有的 <a> 标签。

document.addEventListener("DOMContentLoaded", () => {
  [].forEach.call(document.getElementsByTagName("a"), (element) => {
    element.addEventListener("click", (event) => {
      event.preventDefault(); // Block the page from loading
      alert(element.href); // Show an alert with the url in the href
    });
  });
});
<a href="https://www.google.com">Click me</a>

相关问题