开发者

JavaScript not executing correctly in address bar

I am trying to execute the following in the browsers address bar:

javascript:document.getElementById('Input').value='0'

But it does something completely different and just displays 0 on the screen. Why is开发者_高级运维 this happening and how to execute the JavaScript correctly to assign 0 as a value of #input using the address bar.


For some reason you need to add ;void 0 to the end of scripts that you run in the address bar to prevent a new page from being loaded.

Also check the js error console to see if there are any errors (like if the element doesn't exist)


getElementById returns one element, not an array, which is why your statement isn't working properly. Remove the [0] and it might work.

You seem to be also looking for an input element, so if you don't have an element with id="input", you can use getElementsByTagName (notice the s).

It returns all elements with a given tag name:

javascript:document.getElementsByTagName('input')[0].value='0'


When you run a javascript: URI, the return value of the script, if it's not undefined, is converted to a string. That string is then loaded as HTML. The return value is just the value of the last statement executed by the script.

You can see this pretty simply by putting this in your URL bar: javascript:"<h1>Hey</h1>".

In your case, the return value of your script is the string '0', which is exactly what you then see parsed as HTML.

You can force the return value to be undefined by putting something guaranteed to evaluate to undefined at the end of your script. void 0 is a popular choice.


You may want to try getElementByType('input')[0] instead...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜