简体   繁体   English

引用输入字段的值

[英]Reference to the value of input field

Consider the following code snippet: 请考虑以下代码段:

inputTextField=document.getElementById("Phone_input");
var value = inputTextField.value; 
value=value.substring(0,10);

where Phone_input is an <input type="text"/> element. 其中Phone_input<input type="text"/>元素。 Why during the running of this script there is no changes of actual value of the <input type="text"/> . 为什么在运行此脚本期间, <input type="text"/>的实际值没有变化。 We're changing value by the reference which indicates to inputTextField.value . 我们通过指示inputTextField.value的引用来更改值。

The variable value is not a reference, so after the change you must write it back into the textfield: 变量value不是引用,因此在更改之后,您必须将其写回文本字段:

value=value.substring(0,10);
inputTextField.value = value;

Or, in one line: 或者,在一行中:

inputTextField.value = inputTextField.value.substring(0,10);

Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents. Javascript总是按值传递,但在数组或对象中,值是对它的引用,因此您可以“更改”内容。 In this case you have to do it this way: 在这种情况下,你必须这样做:

var inputTextField=document.getElementById("Phone_input");
inputTextField.value = inputTextField.value.substring(0,10);

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

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