您是否需要在 onclick 中指定“javascript:"? [英] Do you ever need to specify 'javascript:' in an onclick?

查看:23
本文介绍了您是否需要在 onclick 中指定“javascript:"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AFAIK,你永远不需要在点击时指定协议:

AFAIK, you never need to specify the protocol in an onclick:

onclick="javascript:myFunction()" 糟糕

onclick="myFunction()"

今天我注意到 这篇关于 Google 分析的文章他们正在使用它:

Today I noticed in this article on Google Anallytics that they are using it:

<a href="http://www.example.com" onClick="javascript: pageTracker._trackPageview('/outgoing/example.com');">

这个例子是完全错误的,还是有理由在 href 以外的任何东西中指定 javascript: ?

Is this example just plain wrong, or is there ever a reason to specify javascript: in anything other than a href?

推荐答案

这里的一些回复声称javascript:"前缀是旧时代的遗留物",暗示它是有意的,由浏览器专门处理为了向后兼容.是否有确凿的证据表明情况确实如此(有没有人检查过源代码)?

Some of the responses here claim that the "javascript:" prefix is a "leftover from the old days", implying that it's intentionally, specially handled by the browsers for backwards compatibility. Is there solid evidence that this is the case (has anyone checked source code)?

<span onclick="javascript:alert(42)">Test</span>

对我来说,这只是:

javascript:
    alert(42);

意思是,javascript:"只是一个标签,没有任何作用.这也有效:

Meaning, that "javascript:" is just a label and has no effect. This works, too:

<span onclick="foobar:alert(42)">Test</span>

更新:

我做了一个小实验,结果是,javascript:"是由 IE 专门处理的,但 Firefox、Safari、Opera 或 Chrome 绝对不是这样:

I did a little experiment and it turns out that, yes, "javascript:" is handled specially by IE, but definitely not so by Firefox, Safari, Opera or Chrome:

<span onclick="javascript:while (true) { alert('once'); break javascript; }">Test</span>

在非 IE 上,这只会提醒一次",一次然后跳出循环.在 IE 上,我收到找不到标签"错误.以下适用于所有浏览器:

On non-IE, this will just alert "once", once and then break out of the loop. On IE, I get a "Label not found" error. The following works fine in all browsers:

<span onclick="foo:while (true) { alert('once'); break foo; }">Test</span>

更新 2:

我刚刚意识到链接http://crisp.tweakblogs.net/blog/the-useless-javascript-pseudo-protocol.html 在上面的一个答案中几乎谈到了同样的事情.

I just realized the link http://crisp.tweakblogs.net/blog/the-useless-javascript-pseudo-protocol.html in one of the answers above pretty much talks about the same thing.

这篇关于您是否需要在 onclick 中指定“javascript:"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆