undo preventDefault() or better way to programmatically disable collections of links

六眼飞鱼酱① 提交于 2019-12-05 08:53:00

You seem to be using jQuery, at least for the link handler part.

The thing to realize is that $.click(handler) is just shorthand for .bind('click', handler). If you define the handler elsewhere, you can also unbind it later, like this:

var handler = function(event) { 
  event.preventDefault();
  console.log("the links, they do nothing!");
}

// when you want the external links to be inactive.
// you could use .click(handler) here too, it's the same.
$('a[href^="http"]').bind('click', handler);

// when you want them back
$('a[href^="http"]').unbind('click', handler);

By the way, href^="http" is a bit fragile, if you only want this to happen to external links. Internal links might start with "http", and some external links could start with other protocols like "ftp". Better to give such links their own class, like Wikipedia does with 'external'.

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