admin管理员组文章数量:1279042
What is javascript:
in a JavaScript event handler?
Such as:
<input onkeydown="javascript:return false;" type="text" name="textfield" />
What is javascript:
in a JavaScript event handler?
Such as:
<input onkeydown="javascript:return false;" type="text" name="textfield" />
Share
Improve this question
edited Mar 23, 2023 at 12:55
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Jun 1, 2011 at 9:28
user635409user635409
1
- possible duplicate of Do you ever need to specify 'javascript:' in an onclick? – Bergi Commented Sep 8, 2013 at 9:44
5 Answers
Reset to default 9It is a mistake. The pseudo-protocol is not needed in event handlers.
On a URL (a
element href
attribute, for instance), if you enter javascript:
and follow that with javascript, the browser will run the javascript code.
For event handler, this is not needed, though the browser will not report an error.
In this case it will be interpreted as label. You could also write foobar:
here, it would have the same effect.
It is not really needed in JavaScript code (I have never seen it used in real code), though it could be useful:
Provides a statement with an identifier that you can refer to using a
break
orcontinue
statement.For example, you can use a label to identify a loop, and then use the
break
orcontinue
statements to indicate whether a program should interrupt the loop or continue its execution.
In your case, the markup should just be:
<input onkeydown="return false;" type="text" name="textfield" />
But if you use it as scheme in an URI, it tells the browser to interpret and execute the URI as JavaScript:
<a href="javascript:alert(1);">Foo</a>
(I'm not saying you should do something like this.)
I assume people less familiar with JavaScript see this and think they have to put javascript:
everywhere in front of JavaScript code in HTML, also in event handlers.
You can just write return false
. At that time the javascript
protocol was useful in links. href
attribute: <a href="javascript:return false">
It's something that shouldn't be there.
The javascript:
prefix is primarily used for links, as the javascript:
protocol in a browser would generally execute the code, for example:
<a href="javascript:alert('test')">Test</a>
In an event handler, though, it's already parsing JavaScript, thus it is not required. It's basically doing nothing.
It's just markup to tell the browser that what follows is JavaScript code. However, it is not needed, so you don't have to include it.
本文标签: What is quotjavascriptquot in a JavaScript event handlerStack Overflow
版权声明:本文标题:What is "javascript:" in a JavaScript event handler? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741215927a2360043.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论