简体   繁体   English

输入值不会改变

[英]Input value won't change

I'm having some trouble getting my input value to change when I type a value inside it. 当我在其中输入一个值时,我在输入值变化时遇到了一些麻烦。

 var t = document.createElement('div'); t.innerHTML = '<input type="text" id="myText">'; document.getElementById("news").appendChild(t); var x = document.getElementById("myText").value; //Grabs the value of the input. t.onchange = function(){myFunction()} //Input. Onchange.. function myFunction() { console.log(x); //Logs the value of "x" } 

My problem is when I type some string in the input. 我的问题是当我在输入中键入一些字符串。 "Hello world" as a example. 以“Hello world”为例。 It should print "Hello world" to the console. 它应该在控制台上打印“Hello world”。 Instead it prints nothing. 相反它什么都不打印。 Just a blank line. 只是一个空白行。 How could I make it to print what I type inside the input box? 我怎么能打印出输入框内输入的内容?

Using my script. 使用我的脚本。

  1. The 'change' event fires only when you leave the input field. 只有在离开输入字段时才会触发“更改”事件。 You probably want an 'input' event here which fires immediately and the listener is registered with oninput 您可能希望此处的“输入”事件立即触发,并且侦听器已在oninput上注册
  2. x is a variable that's initialized just once and variables are not bound to the current value of whatever you used to initialize them so you need to read the element's value again x是一个仅初始化一次的变量,并且变量未绑定到用于初始化它们的任何内容的当前值,因此您需要再次读取元素的值
  3. bind a function directly to the the event so it can use this to access the element directly 直接结合的功能所涉及的事件,以便它可以使用this直接访问元件
  4. add the event on the input element, not on the div 在输入元素上添加事件,而不是在div上

document.getElementById("myText").oninput = myFunction;

function myFunction() {
  console.log(this.value)
}

Since we don't have onchange on div, it's on input element. 因为我们在div上没有onchange ,所以它在输入元素上。

Difference between onchange & onkeyup . onchangeonkeyup之间的区别。 (MDN) (MDN)

onkeyup — The keyup event fires when the user releases a key that was previously pressed. onkeyup - 当用户释放先前按下的键时,将触发keyup事件。

So, whenever you change value it gets triggered. 因此,每当您更改值时,它都会被触发。

onchange — change events fire when the user commits a value change to a form control. onchange - 当用户将值更改提交到表单控件时触发更改事件。 This may be done, for example, by clicking outside of the control or by using the Tab key to switch to a different control. 例如,可以通过单击控件外部或使用Tab键切换到其他控件来完成此操作。

So, unless you tab or click outside of input your function won't get called. 因此,除非您在输入外部tab或单击,否则您的函数将不会被调用。

You should replace your code with following. 您应该用以下代码替换您的代码。

 var t = document.createElement('div'); t.innerHTML = '<input type="text" id="myText">' document.getElementById("news").appendChild(t); var input = document.getElementById('myText'); input.onkeyup = myFunction function myFunction() { var x = document.getElementById("myText").value; //Grabs the value of the input. console.log(x); //Logs the value of "x" } 
 <div id="news"/> 

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

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