prevent anchor tag from navigating to home page

落花浮王杯 提交于 2019-12-06 12:34:42
Evan Larsen

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

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

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