简体   繁体   English

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

[英]How to get an input text value in JavaScript

How go get an input text value in JavaScript? go如何获取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;当我放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.在 function kk()之外,如上所示,它不起作用,但是当我把它放在里面时,它起作用了。 Can anyone tell me why?谁能告诉我为什么?

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.lol在它之外定义时,你的函数不起作用的原因是因为当 JavaScript 第一次运行时DOM还没有加载。 Because of that, getElementById will return null ( see MDN ).因此, 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.注意<body>标签的onload属性。 (On a side note: the language attribute of the <script> tag is deprecated. Don't use it.) (附带说明: <script>标签的language属性已被弃用。不要使用它。)

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 ).另一种选择是等到 DOM 准备好(通常比onload早得多)。 This can be done with "plain" JavaScript, but it's much easier to use a DOM library like jQuery .这可以使用“普通”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. jQuery 的.ready()将函数作为参数。 The function will be run as soon as the DOM is ready.该函数将在 DOM 准备好后立即运行。 This second example also uses .click() to bind kk's onclick handler, instead of doing that inline in the HTML.第二个示例还使用.click()来绑定 kk 的onclick处理程序,而不是在 HTML 中进行内联。

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:如果你坚持在函数kk之外设置var lol ,那么我提出这个解决方案:

<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.请注意, script元素必须跟在它所引用的input元素之后,因为只有在元素已经被解析和创建的情况下才可以使用getElementById查询元素。

Both examples work, tested in jsfiddler.两个例子都有效,在 jsfiddler 中测试过。

Edit : I removed the language="javascript" attribute, because it's deprecated.编辑:我删除了language="javascript"属性,因为它已被弃用。 See W3 HTML4 Specification, the SCRIPT element :参见W3 HTML4 规范,SCRIPT 元素

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. […] 不推荐使用的元素在未来的 HTML 版本中可能会过时。 […] This specification includes examples that illustrate how to avoid using deprecated elements. […] 该规范包括说明如何避免使用不推荐使用的元素的示例。 […] […]

<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用这个

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).将您的 javascript 移动到页面的末尾,以确保在访问它们之前加载 DOM(html 元素)(javascript 以结束快速加载)。
  2. Declare your variables always like in example using var textInputVal = document.getElementById('textInputId').value;使用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要查看有关 getElementById 的更多信息,请参阅: 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使用 jQuery 等库使使用 javascript 变得容易一百倍,要了解更多信息: http : //docs.jquery.com/Tutorials : Getting_Started_with_jQuery

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 .您的代码被逐行解析,并且lol = ...行在浏览器知道具有 id lolz的输入的存在之前进行评估。 Thus, document.getElementById('lolz') will return null , and document.getElementById('lolz').value should cause an error.因此, 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 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.将所有脚本块移动到 HTML <body>的末尾是当今避免此类引用问题的标准做法。 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 之后处理的。

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´sa wonderful day!" id="textbox"/> <input type="button" value="Show this message!" onClick="showMessage()" /> </div>

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

All the above solutions are useful.以上所有解决方案都是有用的。 And they used the line他们使用了这条线

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

inside the function function kk() .在函数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.当您构建复杂的项目时,它会很有用。

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

document.getElementById('id').value

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.然后它会提醒现在等于文本框输入的变量。

You can simply get values by using JavaScript (e) event object.您可以使用 JavaScript (e)事件 object 简单地获取值。

<body>
  <form onsubmit="handleSubmit()">
    <input type="text" name="name"/>
    <input type="email" name="email"/>
    <input type="password" name="password"/>
    <input type="submit" value="Submit"/>
  </form>
</body>
const handleSubmit = (e) =>
{
  e.preventDefault(); // prevent reload while click submit button
  const name = e.target.name.value;
  const email = e.target.email.value;
  const password = e.target.password.value;
  // do something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM