location.href跳转和给a标签设置点击事件有什么区别

我本来用的是window.location.href=url来跳转都相关的页面,但是在某些第三方app里,发现好像不管用了,看别人的代码,他是先创建一个隐藏的a标签,然后给这个a标签一个click事件,执行跳转:

var a = document.createElement("a");

a.setAttribute("href", aV);
a.style.display = "none";

var ev = document.createEvent('HTMLEvents');

ev.initEvent('click', false, true);
a.dispatchEvent(ev);

那么请问location.href跳转和给a标签设置点击事件有什么区别呢?

阅读 10.8k
1 个回答

Wherever possible, you should use <a href="foo.html"> over window.location.href, for a number of very good reasons.

If you have javascript disabled, none of the links would work.
Spiders, such as Google Bot, do not interpret javascript, and so they won't follow any of your links.
IT BREAKS THE INTERNET. No, really though - the World Wide Web is built on the very basis of discoverable linkages between pages. Hiding these linkages with non-standard .. err, links, goes against that very premise.
It makes for a bad user experience: a user expects that when they mouse over a link, they will have access to some information:
the destination displayed in the status bar (very important!)
right-click -> copy link location
middle-click -> open new tab
etc
Using window.location breaks all of these
It's much easier!

Reference: https://stackoverflow.com/que...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题