使用“javascript://”是错误的或不好的做法。作为阻止行动的链接?
我刚刚看到这个问题 这让我想起了我通常会做的事情来阻止某些链接的默认操作:
<a href="javascript://">something</a>
然后我用 jQuery 单击函数来处理它。我已经在某些地方看到人们使用
<a href="javascript:void(0)">something</a>
我知道更好的方法是使用
e.preventDefault();
但是我所做的事情是错误的还是不好的做法?这实际上是如何运作的?
I just saw this question
and it reminds me of something I usually do to prevent the default action of some link:
<a href="javascript://">something</a>
Then I handle it with jQuery click function. I already saw in some places people using
<a href="javascript:void(0)">something</a>
I know the better way is using
e.preventDefault();
But is it wrong or a bad practice to do what I do? How this actually works?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这有点不幸,因为如果用户按住 Ctrl 键单击或右键单击并说“在新选项卡中打开”,他们将得到一个完全空白的页面。
使用
something
加上preventDefault
会更好,因为在这种情况下 Ctrl+click 只会将它们带回他们所在的页面都在。当然,最好的情况是您可以让
href
指向实际有意义的页面,而 JavaScript 会逐步增强体验并覆盖有意义的默认值。弹出窗口就是一个很好的例子,但是只要多做一点工作就可以做到这一点。It's a bit unfortunate because if the user Ctrl+clicks or right clicks and says "Open in New Tab," they will get a completely blank page.
Using
<a href="#">something</a>
pluspreventDefault
is better, since in that case Ctrl+click just takes them back to the page they were on.Of course, the very best is if you can have the
href
point to a page that is actually meaningful, with the JavaScript being a progressive enhancement to the experience that overrides that meaningful default. A great example of this is popup windows, but with a bit more work anything can be made to do this.这是不好的做法,因为存在更好的机制,那就是
event.preventDefault()
。此外,
javascript:
伪协议只能用于小书签。It is bad practice because a better mechanism exists and that is
event.preventDefault()
.Also, the
javascript:
pseudo protocol should only be used for bookmarklets.