What is javascript:
开发者_运维技巧in a JavaScript event handler?
Such as:
<input onkeydown="javascript:return false;" type="text" name="textfield" />
It 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.
精彩评论