防止锚标签导航到主页 [英] prevent anchor tag from navigating to home page

查看:51
本文介绍了防止锚标签导航到主页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个常规的定位标记,其href属性设置为#。通常,这会阻止任何导航,但在durandal中,它会将我导航到主视图。如何阻止它导航到该视图?
我无法更改html和样式。它必须是那个锚标签。但是我可以将click事件绑定到它。有什么方法可以取消锚点事件中的导航?

I have a regular anchor tag with href attribute set to "#". Normally, this prevents from any navigation but in durandal it navigates me to the home view. How can I stop it from navigating to that view? I can't change the html and stylings. It needs to be that anchor tag. But I can bind a click event to it. Is there any way to cancel navigation in anchor click event?

注意事项

推荐答案

绑定一个单击事件并调用event.preventDefault()

Bind a click event to it and call event.preventDefault()

<a href="#" id="someAnchor">Example</a>

$(function() {
   $('#someAnchor').click(function(event) { event.preventDefault(); });
});

这将阻止浏览器传播click事件,并且什么也不会发生。但是在click事件中,您可以执行所需的任何逻辑。

This will prevent the browser from propagating the click event and nothing will happen. But inside the click event you can do whatever logic you want.

如果您使用敲除来绑定click事件,请请参阅此stackoverflow帖子,了解如何从敲除绑定中进行操作。

If you are using knockout to bind the click event then please refer to this stackoverflow post on how to do it from a knockout binding.

编辑** Per Tyrsius的评论是使用基因剔除绑定来绑定点击事件的一种较好做法。

EDIT ** Per Tyrsius' comments its a better practice to use the knockout binding to bind a click event.

因此,建议您执行以下操作:

So, instead it is recommended you do:

<a href="#" data-bind="click: clickHandler">ClickMe</a>

clickhandler = function (e) {
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
};

这篇关于防止锚标签导航到主页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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