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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11810874/
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-24 07:11:30  来源:igfitidea点击:

How to get an input text value in JavaScript

javascripttextinputget

提问by Maria

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').value;函数之外时kk(),如上所示,它不起作用,但当我把它放在里面时,它起作用。谁能告诉我为什么?

回答by Peter-Paul van Gemerden

The reason you function doesn't work when lolis defined outside it, is because the DOMisn't loaded yet when the JavaScript is first run. Because of that, getElementByIdwill return null(see MDN).

lol在它之外定义时,您的函数不起作用的原因是因为在第一次运行 JavaScript 时还没有加载DOM。因此,getElementById将返回null参见 MDN)。

You've already found the most obvious solution: by calling getElementByIdinside 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 onloadattribute of the <body>tag. (On a side note: the languageattribute of the <script>tag is deprecated. Don't use it.)

注意标签的onload属性<body>(附带说明:标签的language属性<script>已被弃用。不要使用它。)

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 onclickhandler, instead of doing that inline in the HTML.

jQuery 的.ready()将函数作为参数。该函数将在 DOM 准备好后立即运行。第二个示例也使用.click()来绑定 kk 的onclick处理程序,而不是在 HTML 中进行内联。

回答by nalply

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 lolto 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 scriptelement must follow the inputelement it refers to, because elements are only queryable with getElementByIdif they already have been parsed and created.

请注意,script元素必须跟在input它所引用的元素之后,因为元素只有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:

编辑:我删除了该language="javascript"属性,因为它已被弃用。请参阅W3 HTML4 规范,SCRIPT 元素

language= 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 deprecatedin favor of type.

语言= cdata[ CI]

已弃用。此属性指定此元素内容的脚本语言。它的值是语言的标识符,但由于这些标识符不是标准的,因此该属性已被弃用,以支持类型。

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 版本中可能会过时。[…] 该规范包括说明如何避免使用已弃用元素的示例。[…]

回答by DOCTYPE HTML

<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

用这个

回答by Mauno V?h?

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. Declare your variables always like in example using var textInputVal = document.getElementById('textInputId').value;
  3. Use descriptive names for inputs and elements (makes easier to understand your own code and when someone other is looking it).
  4. To see more about getElementById, see: http://www.tizag.com/javascriptT/javascript-getelementbyid.php
  5. Using library such as jQuery makes using javascript hundred times easier, to learn more: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
  1. 将您的 javascript 移动到页面的末尾,以确保在访问它们之前加载 DOM(html 元素)(javascript 以结束快速加载)。
  2. 使用var textInputVal = document.getElementById('textInputId').value;始终像示例中一样声明您的变量
  3. 为输入和元素使用描述性名称(更容易理解您自己的代码以及当其他人正在查看它时)。
  4. 要查看有关 getElementById 的更多信息,请参阅:http: //www.tizag.com/javascriptT/javascript-getelementbyid.php
  5. 使用 jQuery 等库使使用 javascript 变得容易一百倍,要了解更多信息:http: //docs.jquery.com/Tutorials: Getting_Started_with_jQuery

回答by bfavaretto

Notice that this line:

请注意这一行:

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

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

<input>标记的实际元素之前:

<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').valueshould cause an error.

您的代码被逐行解析,并且lol = ...在浏览器知道具有 id 的输入的存在之前评估该行lolz。因此,document.getElementById('lolz')将返回null,并且document.getElementById('lolz').value应该导致错误。

Move that line inside the function, and it should work. This way, that line will only run when the function is called. And use varas 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 的末尾<body>是当今避免此类引用问题的标准做法。它还倾向于加快页面加载速度,因为加载和解析需要很长时间的脚本是在(大部分)显示 HTML 之后处理的。

回答by Jorgesys

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>

回答by harsh mangalam

<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>

回答by Shreedhar

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);
}

回答by htoniv

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

以上所有解决方案都是有用的。他们lol = document.getElementById('lolz').value;在函数内部使用了这一行function 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.

当您构建复杂的项目时,它会很有用。

回答by Scott

<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>