[英]Why do I need to write “javascript:” before a function name?
If I want to use an external javascipt function like "functionname()", see the example below: 如果要使用外部Javascipt函数(例如“ functionname()”),请参见以下示例:
<from onSubmit="javascript: funtionname()" >
</form>
why do I need sometimes to write javascript: before the function name? 为什么有时需要在函数名称前写javascript :?
In handlers ( onclick
, onchange
, etc.), you don't have to use the prefix. 在处理程序(
onclick
, onchange
等)中,您不必使用前缀。 For these, Javascript is already expected and the prefix is interpreted as a label and has no effect. 对于这些,已经期望使用Javascript,并且前缀将被解释为标签,并且无效。
If you want to execute Javascript in an href
attribute for example, the prefix "javascript:" is needed. 例如,如果要在
href
属性中执行Javascript, 则需要前缀“ javascript:”。 Otherwise the value would be interpreted as a URL. 否则,该值将被解释为URL。
In general, though, this practice should be avoided as it contradicts unobtrusive Javascript policy. 但是,一般而言,应避免这种做法,因为它与不干扰Javascript策略的行为相矛盾。
The javascript:
notation is a URL scheme, and may be used wherever a URL is expected. javascript:
表示法是URL方案,可以在需要URL的任何地方使用。 As far as I am aware, passing a URL to an event handler is incorrect (at least according to the HTML5 spec) though browsers appear to support it. 据我所知,尽管浏览器似乎支持将URL传递给事件处理程序是不正确的(至少根据HTML5规范)。 You are expected to specify a valid function or null as an event handler.
您应该指定一个有效的函数或将null指定为事件处理程序。 The browser may be interpreting this javascript prefix as a label, though it might be technically incorrect to allow this.
浏览器可能将此javascript前缀解释为标签,尽管从技术上讲不允许这样做。
You don't. 你不知道
You will need to write javascript:
when you using an url type tag only (like: href
and src
), to specify that the string need to eval a javascript code. 您将只需要编写
javascript:
当您仅使用url类型标记(例如: href
和src
)时,指定该字符串需要评估javascript代码。
Example: 例:
<a href="javascript: doSomething();">
My link is a javascript function doSomething()
</a>
You can: 您可以:
<form onSubmit="doSomething();">
When submit the form, will ran doSomething,
if returns false will cancel the form submission
</form>
No need to do it in handlers. 无需在处理程序中执行此操作。 It is used only as protocol in URL-like method, eg:
它仅用作类似URL的方法中的协议,例如:
<a href="javascript:funtionname()">Click here</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.