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

发布于 2022-09-07 04:21:22 字数 412 浏览 34 评论 0

我本来用的是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标签设置点击事件有什么区别呢?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柏林苍穹下 2022-09-14 04:21:22

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文