prevent anchor tag from navigating to home page

混江龙づ霸主 提交于 2019-12-08 01:18:30

问题


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?

regards


回答1:


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

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

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

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.

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.

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



回答2:


Have all your anchor links start with a prefix. Then have in your router.guardRoute function this:

if (_.startsWith(instruction.fragment, YOUR_PREFIX))
      return false;
}

Worked well for me and no need to add anything else to your app views.

PS. _.startsWith is lodash function. If not using lodash do JS string indexOf or whatever



来源:https://stackoverflow.com/questions/18145960/prevent-anchor-tag-from-navigating-to-home-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!