window.location 相对于 href 标签的潜在优点/缺点?
I inherited some code with <img src="../...gif" onclick="aURL">
.
I was wondering the reason behind this choice so I would like to know any potential advantages/disadvantages of window.location over a tag with href?
I am considering changing to <a href="aURL"><img src="../...gif"></a>
.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我立即发现
![]()
方法的主要缺点是各种形式的点击都不起作用,例如 Ctrl+click 在新窗口中打开选项卡、Shift+单击在新窗口中打开等。此外,禁用 JavaScript 也是
onclick="window.location=x;"
失败的一个区域。一定要像你想的那样在这里使用锚,这就是它的目的。
The main disadvantage with the
<img onclick="">
approach I immediately see is that various forms of clicks will not work, e.g. Ctrl+click opening in a new tab, Shift+click opening in a new window, etc.Also, JavaScript being disabled is also an area the
onclick="window.location=x;"
fails.Definitely use an anchor here like you're thinking, that's its purpose.
至于原因,我也不好说。
通常,最好在锚点上设置 href,即使您不打算使用它。如果用户没有启用 JavaScript,或者机器人正在抓取您的网站并且不会使用 onclick 事件,则应将 href 设置为后备。如果您必须打开弹出窗口,请将其放入 onclick 中并返回 false,这样它就不会命中 href。我绝对建议从
![]()
中删除 onclick 并将其放入包装中。
As for the reason, I can't speak to that.
Typically, you're always better off setting the href on an anchor, even if you don't intend to use it. The href should be set as a fallback in case the user doesn't have JavaScript enabled, or if a bot is crawling your site and won't use the onclick event. If you have to open a popup, then put that in the onclick and return false so it doesn't hit the href. I would definitely recommend removing the onclick from the
<img>
and putting it in an<a>
wrapping it.