使用 JavaScript 设置表单元素的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6435146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:42:41  来源:igfitidea点击:

Using JavaScript to set the value of a form element

javascripthtml

提问by Nyxynyx

I am currently trying to learn JavaScript and in a particular excercise, I am trying to set the value of a button from a user input, but I keep getting an empty value. Where did I go wrong?

我目前正在尝试学习 JavaScript,并且在一个特定的练习中,我试图从用户输入设置按钮的值,但我一直得到一个空值。我哪里做错了?

<html>
    <head>
        <title>JavaScript Variables</title>
        <script type="text/javascript">
         FIRST_NAME = window.prompt("Enter your first name.");
         document.forms[0].username.value = FIRST_NAME;
        </script>
    </head>
    <body>
        <form id="myForm">
            <input type="button" value="Paul"
              onclick="alert('Paul');"/>
            <br/><br/>
            <input type="button" value="John"
              onclick="alert('John');"/>
            <br/><br/>
            <input type="button" value="George"
              onclick="alert('George');"/>
            <br/><br/>
            <input type="button" value="Ringo"
              onclick="alert('Ringo');"/>
            <br/><br/>
            <input type="button" id="username" name="username" value=''
              onclick="alert(FIRST_NAME);"/>
    </body>
</html>

The error I get is:

我得到的错误是:

Uncaught TypeError: Cannot read property 'username' of undefined

未捕获的类型错误:无法读取未定义的属性“用户名”

回答by Asaph

The problem is that when the contents of the <script>element are executed, the browser has not yet loaded/rendered the referenced form. Try moving the contents of the <script>element into a function and calling that function on the onloadevent.

问题是当<script>元素的内容被执行时,浏览器还没有加载/渲染引用的表单。尝试将<script>元素的内容移动到一个函数中并在onload事件上调用该函数。

<html>
    <head>
     <title>JavaScript Variables</title>
     <script type="text/javascript">
      function init() {
          var FIRST_NAME = window.prompt("Enter your First Name.");
          document.forms[0].username.value = FIRST_NAME;
      }
     </script>
    </head>
    <body onload="init();">
    <form id="myForm">
     <input type="button" value="Paul"
       onclick="alert('Paul');"/>
     <br/><br/>
     <input type="button" value="John"
       onclick="alert('John');"/>
     <br/><br/>
     <input type="button" value="George"
       onclick="alert('George');"/>
     <br/><br/>
     <input type="button" value="Ringo"
       onclick="alert('Ringo');"/>
     <br/><br/>
     <input type="button" id="username" name="username" value=""
       onclick="alert(this.value);"/>
    </body>
</html>

回答by mattn

When shot the prompt, any elements is not loaded. You should do it after loaded.

当拍摄提示时,没有加载任何元素。你应该在加载后做。

<html>
    <head>
        <title>JavaScript Variables</title>
        <script type="text/javascript">
            window.onload = function() {
                FIRST_NAME = window.prompt("Enter your first name.");
                document.forms[0].username.value = FIRST_NAME;
            }
        </script>
    </head>
    <body>
        <form id="myForm">
            <input type="button" value="Paul"
              onclick="alert('Paul');"/>
            <br/><br/>
            <input type="button" value="John"
              onclick="alert('John');"/>
            <br/><br/>
            <input type="button" value="George"
              onclick="alert('George');"/>
            <br/><br/>
            <input type="button" value="Ringo"
              onclick="alert('Ringo');"/>
            <br/><br/>
            <input type="button" id="username" name="username" value=''
              onclick="alert(FIRST_NAME);"/>
    </body>
</html>

回答by Praveen Lobo

Place the script after the HTML element so that when the script is executed, it really has a DOM element to set value to. Try this code, it will tell you what document.forms[0]is when you are trying to access it.

将脚本放在 HTML 元素之后,以便在执行脚本时,它确实有一个 DOM 元素可以设置值。试试这个代码,它会告诉你document.forms[0]当你试图访问它时是什么。

<html>
    <head>
        <title>JavaScript Variables</title>

        <script type="text/javascript">
           alert(typeof document.forms[0]);
        </script>
    </head>
    <body>
        <form id="myForm">
            <input type="button" value="Paul"
                   onclick="alert('Paul');"/>
            <br/><br/>
            <input type="button" value="John"
                   onclick="alert('John');"/>
            <br/><br/>
            <input type="button" value="George"
                   onclick="alert('George');"/>
            <br/><br/>
            <input type="button" value="Ringo"
                   onclick="alert('Ringo');"/>
            <br/><br/>
            <input type="button" id="username" name="username" value=''
                   onclick="alert(FIRST_NAME);"/>

            <script type="text/javascript">
                FIRST_NAME = window.prompt("Enter your first name.");
                document.forms[0].username.value = FIRST_NAME;
            </script>
    </body>
</html>

But a good way of doing it would be to create a function and call its BODY's onload method. Just replace you BODY tag with <body onload="document.forms[0].username.value = window.prompt('Enter your first name.');">and see what happens (of course, remove all other code that you put in to do the same).

但是这样做的一个好方法是创建一个函数并调用其 BODY 的 onload 方法。只需将您的 BODY 标记替换为<body onload="document.forms[0].username.value = window.prompt('Enter your first name.');">,看看会发生什么(当然,删除您输入的所有其他代码以执行相同操作)。

回答by Teddy

Looks like the form tag is not closed. So, maybe there is no valid form in the page and hence document.forms[0] is undefined.

看起来表单标签没有关闭。因此,可能页面中没有有效的表单,因此 document.forms[0] 未定义。

Before the close-body tag, add a close-form tag.

在 close-body 标签之前,添加一个 close-form 标签。