开发者

Use onclick event when JS is enabled, navigate to a URL when it's not

Faceboo开发者_开发问答k uses Ajax links to change parts of their pages in order to keep the load time down. But if you disable JavaScript, their links still work. That's because they've also defined a backup option: the classic <a href="http://url/".

How can I implement this myself so that the link will be followed when JS is disabled and the onclick event will be used when JS is enabled?


In your onclick you do a return false; at the end to prevent the default action, which in this case is actually navigating to the URL, something like this:

document.getElementById('linkId').onclick = function() {
  alert("This link would go to: " + this.href);
  return false;
};

Or, if you're using something like jQuery and event.preventDefault():

$("a").click(function(e) {
  alert("This link would go to: " + this.href);
  return false; //or e.preventDefault();
});


The onclick handler has to return false, then the link won't be followed when js is enabled. Otherwise it will use the href to work normally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜