开发者

javascript getElementsByTagName doesn't work

Is there something wrong with the script? or that getElementsbyTagName is deprecated?

<script>
t=document.getElementsByTagName('input')[0];
document.write(t.value);
&l开发者_JAVA百科t;/script>

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Type here: <input type='text' value="my value is high">


You're trying to do a document.write() presumably before your page is loaded. Therefore, the array returned by getElementsByTagName will be empty because there aren't any tags of any kind available until the document has loaded.

Either handle this from the body.onload event, or else trigger it from some other event. In fact, why would you be trying to get the value of a text input before it could even have any value other than the one you supply (here, 'my value is high'), in which case you could just use that literal value in your document.write()?

I suspect you want to get the value of that input after some user interaction, in which case you might handle the input's onblur event with a function that sets the innerHTML of some other element to the value of the event.currentTarget (which will be your input). So after the user has typed something and exited the input, the value of the input would appear wherever you desire.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜