如何在JavaScript中获取输入文本值

时间:2023-01-28 18:03:27

How go get an input text value in JavaScript?

如何在JavaScript中获取输入文本值?

<script language="javascript" type="text/javascript">
    lol = document.getElementById('lolz').value;
    function kk(){
    alert(lol);
    }
</script>

<body>
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" OnClick="kk()"/>
</body>

When I put lol = document.getElementById('lolz').value; outside of the function kk(), like shown above, it doesn't work, but when I put it inside, it works. Can anyone tell me why?

当我输入lol = document。getelementbyid ('lolz')。在函数kk()之外,如上面所示,它不工作,但是当我把它放在里面时,它就工作了。谁能告诉我为什么吗?

12 个解决方案

#1


61  

The reason you function doesn't work when lol is defined outside it, is because the DOM isn't loaded yet when the JavaScript is first run. Because of that, getElementById will return null (see MDN).

函数在外部定义lol时不能工作的原因是,在第一次运行JavaScript时还没有加载DOM。因此,getElementById将返回null(参见MDN)。

You've already found the most obvious solution: by calling getElementById inside the function, the DOM will be loaded and ready by the time the function is called, and the element will be found like you expect it to.

您已经找到了最明显的解决方案:通过在函数中调用getElementById,在调用函数时,DOM将被加载并准备好,并且元素将像您期望的那样被找到。

There are a few other solutions. One is to wait until the entire document is loaded, like this:

还有一些其他的解决方案。一种是等待整个文档被加载,如下所示:

<script type="text/javascript">
    var lolz;
    function onload() { 
        lolz = document.getElementById('lolz');
    }
    function kk(){
        alert(lolz.value);
    }
</script>

<body onload="onload();">
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" onclick="kk();"/>
</body>

Note the onload attribute of the <body> tag. (On a side note: the language attribute of the <script> tag is deprecated. Don't use it.)

注意标记的onload属性。附带说明:不赞成使用

There is, however, a problem with onload: it waits until everything (including images, etc.) is loaded.

然而,onload有一个问题:它等待所有东西(包括图像等)被加载。

The other option is to wait until the DOM is ready (which is usually much earlier than onload). This can be done with "plain" JavaScript, but it's much easier to use a DOM library like jQuery.

另一个选项是等待DOM准备就绪(通常比onload早得多)。这可以通过“纯”JavaScript完成,但是使用像jQuery这样的DOM库要容易得多。

For example:

例如:

<script type="text/javascript">
    $(document).ready(function() {
        var lolz = $('#lolz');
        var kk = $('#kk');
        kk.click(function() {
            alert(lolz.val());
        });
    });
</script>

<body>
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" id="kk" />
</body>

jQuery's .ready() takes a function as an argument. The function will be run as soon as the DOM is ready. This second example also uses .click() to bind kk's onclick handler, instead of doing that inline in the HTML.

jQuery的.ready()将函数作为参数。一旦DOM准备好,函数就会运行。第二个示例还使用.click()绑定kk的onclick处理程序,而不是在HTML中进行内联操作。

#2


12  

Do not use global variables in this way. Even if this could work, it's bad programming style. You can inadvertently overwrite important data in this way. Do this instead:

不要用这种方式使用全局变量。即使这可以工作,那也是糟糕的编程风格。您可以用这种方式不经意地覆盖重要的数据。这样做:

<script type="text/javascript">
   function kk(){
       var lol = document.getElementById('lolz').value;
       alert(lol);
   }
</script>

If you insist var lol to be set outside the function kk, then I propose this solution:

如果你坚持把var lol设置在函数kk之外,那么我提出这个解决方案:

<body>
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" OnClick="kk()"/>
    <script type="text/javascript">
       var lol = document.getElementById('lolz');
       function kk() {
           alert(lol.value);
       }
    </script>
</body>

Note that the script element must follow the input element it refers to, because elements are only queryable with getElementById if they already have been parsed and created.

注意,脚本元素必须遵循它引用的输入元素,因为只有在元素已经解析和创建之后,才能使用getElementById查询元素。

Both examples work, tested in jsfiddler.

这两个示例都可以在jsfiddler中测试。

Edit: I removed the language="javascript" attribute, because it's deprecated. See W3 HTML4 Specification, the SCRIPT element:

编辑:我删除了语言=“javascript”属性,因为它是不赞成的。参见W3 HTML4规范,脚本元素:

language = cdata [CI]

语言= cdata(CI)

Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.

弃用。此属性指定此元素内容的脚本语言。它的值是语言的标识符,但是由于这些标识符不是标准的,所以不赞成使用类型。

and

A deprecated element or attribute is one that has been outdated by newer constructs. […] Deprecated elements may become obsolete in future versions of HTML. […] This specification includes examples that illustrate how to avoid using deprecated elements. […]

已弃用的元素或属性是被更新的结构过时的元素或属性。[…]废弃的元素在未来的HTML版本中可能会过时。本规范包含了一些示例,说明如何避免使用不赞成使用的元素。[…]

#3


6  

Notice that this line:

请注意,这条线:

lol = document.getElementById('lolz').value;

is before the actual <input> element on your markup:

在您的标记上的实际 <输入> 元素:

<input type="text" name="enter" class="enter" value="" id="lolz"/>

Your code is parsed line by line, and the lol = ... line is evaluated before the browser knows about the existance of an input with id lolz. Thus, document.getElementById('lolz') will return null, and document.getElementById('lolz').value should cause an error.

代码被逐行解析,lol =…在浏览器知道id为lolz的输入存在之前,将对行进行计算。因此,document.getElementById('lolz')将返回null, document.getElementById('lolz')将返回document.getElementById。值应该引起错误。

Move that line inside the function, and it should work. This way, that line will only run when the function is called. And use var as others suggested, to avoid making it a global variable:

在函数中移动这条线,它就会工作。这样,该行只在调用函数时运行。并按照其他人的建议使用var,以避免使其成为全局变量:

function kk(){
    var lol = document.getElementById('lolz').value;
    alert(lol);
}

You can also move the script to the end of the page. Moving all script blocks to the end of your HTML <body> is the standard practice today to avoid this kind of reference problem. It also tends to speed up page load, since scripts that take long to load and parse are processed after the HTML has been (mostly) displayed.

您还可以将脚本移动到页面的末尾。将所有脚本块移动到HTML 的末尾是避免这种引用问题的标准实践。它还会加快页面加载速度,因为需要很长时间加载和解析的脚本会在(大部分)显示HTML之后进行处理。

#4


6  

Edit:

编辑:

  1. Move your javascript to end of the page to make sure DOM (html elements) is loaded before accessing them (javascript to end for fast loading).
  2. 将您的javascript移动到页面的末端,以确保在访问DOM (html元素)之前加载(javascript结束快速加载)。
  3. Declare your variables always like in example using var textInputVal = document.getElementById('textInputId').value;
  4. 例如,使用var textInputVal = document.getElementById('textInputId').value声明变量;
  5. Use descriptive names for inputs and elements (makes easier to understand your own code and when someone other is looking it).
  6. 对输入和元素使用描述性名称(这样更容易理解您自己的代码,以及当其他人查看它时)。
  7. To see more about getElementById, see: http://www.tizag.com/javascriptT/javascript-getelementbyid.php
  8. 有关getElementById的更多信息,请参见:http://www.tizag.com/javascript /javascript-getelementbyid.php
  9. Using library such as jQuery makes using javascript hundred times easier, to learn more: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
  10. 使用jQuery之类的库可以让使用javascript轻松百倍,了解更多信息:http://docs.jquery.com/tutorial:Getting_Started_with_jQuery

#5


6  

<script type="text/javascript">
function kk(){
    var lol = document.getElementById('lolz').value;
    alert(lol);
}


</script>

<body onload="onload();">
    <input type="text" name="enter" class="enter" id="lolz" value=""/>
    <input type="button" value="click" onclick="kk();"/>
</body>

use this

使用这个

#6


2  

as your lol is local variable now, its good practice to use var keyword for declaring any variables.

由于lol现在是局部变量,所以使用var关键字声明任何变量是很好的做法。

this may work for you :

这可能对你有用:

function kk(){
  var lol = document.getElementById('lolz').value;
  alert(lol);
}

#7


2  

All the above solutions are useful. And they used the line lol = document.getElementById('lolz').value; inside the function function kk().

以上所有的解决方案都是有用的。他们使用line lol = document.getElementById('lolz').value;在函数函数kk()中。

What I suggest is, you may call that variable from another function fun_inside()

我的建议是,您可以从另一个函数fun_inside()调用该变量

function fun_inside()
{    
lol = document.getElementById('lolz').value;
}
function kk(){
fun_inside();
alert(lol);
}

It can be useful when you built complex projects.

当您构建复杂的项目时,它可能是有用的。

#8


2  

<script>
function subadd(){
subadd= parseFloat(document.forms[0][0].value) + parseFloat(document.forms[0][1].value) 
window.alert(subadd)  
}
</script>

<body>
<form>
<input type="text" >+
<input type="text" >
<input type="button" value="add" onclick="subadd()">
</form>
</body>

#9


2  

<input type="password"id="har">
<input type="submit"value="get password"onclick="har()">
<script>
    function har() {
        var txt_val;
        txt_val = document.getElementById("har").value;
        alert(txt_val);
    }
</script>

#10


1  

document.getElementById('id').value

. getelementbyid(“id”)value

#11


1  

How to get an input text value in JavaScript

如何在JavaScript中获取输入文本值

    var textbox;
    function onload() { 
        //Get value.
        textbox = document.getElementById('textbox');
    }

    function showMessage() { 
        //Show message in alert()
        alert("The message is: " + textbox.value);
    }
<body onload="onload();">
<div>
<input type="text" name="enter" class="enter" placeholder="Write something here!" value="It´s a wonderful day!" id="textbox"/>
<input type="button" value="Show this message!" onClick="showMessage()" />
</div>

#12


0  

The reason that this doesn't work is because the variable doesn't change with the textbox. When it initially runs the code it gets the value of the textbox, but afterwards it isn't ever called again. However, when you define the variable in the function, every time that you call the function the variable updates. Then it alerts the variable which is now equal to the textbox's input.

之所以不能,是因为变量不会随着文本框而改变。当它最初运行代码时,它会得到文本框的值,但是之后它就不会再被调用了。但是,当您在函数中定义变量时,每次调用函数时,变量都会更新。然后它通知变量,现在它等于文本框的输入。

#1


61  

The reason you function doesn't work when lol is defined outside it, is because the DOM isn't loaded yet when the JavaScript is first run. Because of that, getElementById will return null (see MDN).

函数在外部定义lol时不能工作的原因是,在第一次运行JavaScript时还没有加载DOM。因此,getElementById将返回null(参见MDN)。

You've already found the most obvious solution: by calling getElementById inside the function, the DOM will be loaded and ready by the time the function is called, and the element will be found like you expect it to.

您已经找到了最明显的解决方案:通过在函数中调用getElementById,在调用函数时,DOM将被加载并准备好,并且元素将像您期望的那样被找到。

There are a few other solutions. One is to wait until the entire document is loaded, like this:

还有一些其他的解决方案。一种是等待整个文档被加载,如下所示:

<script type="text/javascript">
    var lolz;
    function onload() { 
        lolz = document.getElementById('lolz');
    }
    function kk(){
        alert(lolz.value);
    }
</script>

<body onload="onload();">
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" onclick="kk();"/>
</body>

Note the onload attribute of the <body> tag. (On a side note: the language attribute of the <script> tag is deprecated. Don't use it.)

注意标记的onload属性。附带说明:不赞成使用

There is, however, a problem with onload: it waits until everything (including images, etc.) is loaded.

然而,onload有一个问题:它等待所有东西(包括图像等)被加载。

The other option is to wait until the DOM is ready (which is usually much earlier than onload). This can be done with "plain" JavaScript, but it's much easier to use a DOM library like jQuery.

另一个选项是等待DOM准备就绪(通常比onload早得多)。这可以通过“纯”JavaScript完成,但是使用像jQuery这样的DOM库要容易得多。

For example:

例如:

<script type="text/javascript">
    $(document).ready(function() {
        var lolz = $('#lolz');
        var kk = $('#kk');
        kk.click(function() {
            alert(lolz.val());
        });
    });
</script>

<body>
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" id="kk" />
</body>

jQuery's .ready() takes a function as an argument. The function will be run as soon as the DOM is ready. This second example also uses .click() to bind kk's onclick handler, instead of doing that inline in the HTML.

jQuery的.ready()将函数作为参数。一旦DOM准备好,函数就会运行。第二个示例还使用.click()绑定kk的onclick处理程序,而不是在HTML中进行内联操作。

#2


12  

Do not use global variables in this way. Even if this could work, it's bad programming style. You can inadvertently overwrite important data in this way. Do this instead:

不要用这种方式使用全局变量。即使这可以工作,那也是糟糕的编程风格。您可以用这种方式不经意地覆盖重要的数据。这样做:

<script type="text/javascript">
   function kk(){
       var lol = document.getElementById('lolz').value;
       alert(lol);
   }
</script>

If you insist var lol to be set outside the function kk, then I propose this solution:

如果你坚持把var lol设置在函数kk之外,那么我提出这个解决方案:

<body>
    <input type="text" name="enter" class="enter" value="" id="lolz"/>
    <input type="button" value="click" OnClick="kk()"/>
    <script type="text/javascript">
       var lol = document.getElementById('lolz');
       function kk() {
           alert(lol.value);
       }
    </script>
</body>

Note that the script element must follow the input element it refers to, because elements are only queryable with getElementById if they already have been parsed and created.

注意,脚本元素必须遵循它引用的输入元素,因为只有在元素已经解析和创建之后,才能使用getElementById查询元素。

Both examples work, tested in jsfiddler.

这两个示例都可以在jsfiddler中测试。

Edit: I removed the language="javascript" attribute, because it's deprecated. See W3 HTML4 Specification, the SCRIPT element:

编辑:我删除了语言=“javascript”属性,因为它是不赞成的。参见W3 HTML4规范,脚本元素:

language = cdata [CI]

语言= cdata(CI)

Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.

弃用。此属性指定此元素内容的脚本语言。它的值是语言的标识符,但是由于这些标识符不是标准的,所以不赞成使用类型。

and

A deprecated element or attribute is one that has been outdated by newer constructs. […] Deprecated elements may become obsolete in future versions of HTML. […] This specification includes examples that illustrate how to avoid using deprecated elements. […]

已弃用的元素或属性是被更新的结构过时的元素或属性。[…]废弃的元素在未来的HTML版本中可能会过时。本规范包含了一些示例,说明如何避免使用不赞成使用的元素。[…]

#3


6  

Notice that this line:

请注意,这条线:

lol = document.getElementById('lolz').value;

is before the actual <input> element on your markup:

在您的标记上的实际 <输入> 元素:

<input type="text" name="enter" class="enter" value="" id="lolz"/>

Your code is parsed line by line, and the lol = ... line is evaluated before the browser knows about the existance of an input with id lolz. Thus, document.getElementById('lolz') will return null, and document.getElementById('lolz').value should cause an error.

代码被逐行解析,lol =…在浏览器知道id为lolz的输入存在之前,将对行进行计算。因此,document.getElementById('lolz')将返回null, document.getElementById('lolz')将返回document.getElementById。值应该引起错误。

Move that line inside the function, and it should work. This way, that line will only run when the function is called. And use var as others suggested, to avoid making it a global variable:

在函数中移动这条线,它就会工作。这样,该行只在调用函数时运行。并按照其他人的建议使用var,以避免使其成为全局变量:

function kk(){
    var lol = document.getElementById('lolz').value;
    alert(lol);
}

You can also move the script to the end of the page. Moving all script blocks to the end of your HTML <body> is the standard practice today to avoid this kind of reference problem. It also tends to speed up page load, since scripts that take long to load and parse are processed after the HTML has been (mostly) displayed.

您还可以将脚本移动到页面的末尾。将所有脚本块移动到HTML 的末尾是避免这种引用问题的标准实践。它还会加快页面加载速度,因为需要很长时间加载和解析的脚本会在(大部分)显示HTML之后进行处理。

#4


6  

Edit:

编辑:

  1. Move your javascript to end of the page to make sure DOM (html elements) is loaded before accessing them (javascript to end for fast loading).
  2. 将您的javascript移动到页面的末端,以确保在访问DOM (html元素)之前加载(javascript结束快速加载)。
  3. Declare your variables always like in example using var textInputVal = document.getElementById('textInputId').value;
  4. 例如,使用var textInputVal = document.getElementById('textInputId').value声明变量;
  5. Use descriptive names for inputs and elements (makes easier to understand your own code and when someone other is looking it).
  6. 对输入和元素使用描述性名称(这样更容易理解您自己的代码,以及当其他人查看它时)。
  7. To see more about getElementById, see: http://www.tizag.com/javascriptT/javascript-getelementbyid.php
  8. 有关getElementById的更多信息,请参见:http://www.tizag.com/javascript /javascript-getelementbyid.php
  9. Using library such as jQuery makes using javascript hundred times easier, to learn more: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
  10. 使用jQuery之类的库可以让使用javascript轻松百倍,了解更多信息:http://docs.jquery.com/tutorial:Getting_Started_with_jQuery

#5


6  

<script type="text/javascript">
function kk(){
    var lol = document.getElementById('lolz').value;
    alert(lol);
}


</script>

<body onload="onload();">
    <input type="text" name="enter" class="enter" id="lolz" value=""/>
    <input type="button" value="click" onclick="kk();"/>
</body>

use this

使用这个

#6


2  

as your lol is local variable now, its good practice to use var keyword for declaring any variables.

由于lol现在是局部变量,所以使用var关键字声明任何变量是很好的做法。

this may work for you :

这可能对你有用:

function kk(){
  var lol = document.getElementById('lolz').value;
  alert(lol);
}

#7


2  

All the above solutions are useful. And they used the line lol = document.getElementById('lolz').value; inside the function function kk().

以上所有的解决方案都是有用的。他们使用line lol = document.getElementById('lolz').value;在函数函数kk()中。

What I suggest is, you may call that variable from another function fun_inside()

我的建议是,您可以从另一个函数fun_inside()调用该变量

function fun_inside()
{    
lol = document.getElementById('lolz').value;
}
function kk(){
fun_inside();
alert(lol);
}

It can be useful when you built complex projects.

当您构建复杂的项目时,它可能是有用的。

#8


2  

<script>
function subadd(){
subadd= parseFloat(document.forms[0][0].value) + parseFloat(document.forms[0][1].value) 
window.alert(subadd)  
}
</script>

<body>
<form>
<input type="text" >+
<input type="text" >
<input type="button" value="add" onclick="subadd()">
</form>
</body>

#9


2  

<input type="password"id="har">
<input type="submit"value="get password"onclick="har()">
<script>
    function har() {
        var txt_val;
        txt_val = document.getElementById("har").value;
        alert(txt_val);
    }
</script>

#10


1  

document.getElementById('id').value

. getelementbyid(“id”)value

#11


1  

How to get an input text value in JavaScript

如何在JavaScript中获取输入文本值

    var textbox;
    function onload() { 
        //Get value.
        textbox = document.getElementById('textbox');
    }

    function showMessage() { 
        //Show message in alert()
        alert("The message is: " + textbox.value);
    }
<body onload="onload();">
<div>
<input type="text" name="enter" class="enter" placeholder="Write something here!" value="It´s a wonderful day!" id="textbox"/>
<input type="button" value="Show this message!" onClick="showMessage()" />
</div>

#12


0  

The reason that this doesn't work is because the variable doesn't change with the textbox. When it initially runs the code it gets the value of the textbox, but afterwards it isn't ever called again. However, when you define the variable in the function, every time that you call the function the variable updates. Then it alerts the variable which is now equal to the textbox's input.

之所以不能,是因为变量不会随着文本框而改变。当它最初运行代码时,它会得到文本框的值,但是之后它就不会再被调用了。但是,当您在函数中定义变量时,每次调用函数时,变量都会更新。然后它通知变量,现在它等于文本框的输入。