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
Add a ment  | 

5 Answers 5

Reset to default 9

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 or continue statement.

For example, you can use a label to identify a loop, and then use the break or continue 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