纯 Javascript 监听输入值变化

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

Pure Javascript listen to input value change

javascript

提问by gespinha

Is there any way I can create a constant function that listens to an input, so when that input value changes, something is triggered immediately?

有什么办法可以创建一个监听输入的常量函数,所以当输入值发生变化时,会立即触发某些东西吗?

I am looking for something using pure javascript, no plugins, no frameworks and I can't edit the HTML.

我正在寻找使用纯 JavaScript 的东西,没有插件,没有框架,而且我无法编辑 HTML。

Something, for example:

某事,例如:

When I change the value in the input MyObject, this function runs.

当我更改 input 中的值时MyObject,此函数将运行。

Any help?

有什么帮助吗?

回答by Quentin

This is what eventsare for.

这就是事件的目的。

HTMLInputElementObject.addEventListener('input', function (evt) {
    something(this.value);
});

回答by Niffler

As a basic example...

作为一个基本的例子......

HTML:

HTML:

<input type="text" name="Thing" value="" />

Script:

脚本:

/* event listener */
document.getElementsByName("Thing")[0].addEventListener('change', doThing);

/* function */
function doThing(){
   alert('Horray! Someone wrote "' + this.value + '"!');
}

Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/

这是一个小提琴:http: //jsfiddle.net/Niffler/514gg4tk/

回答by AmerllicA

Actually, the ticked answer is exactly right, but the answer can be in ES6shape:

实际上,打勾的答案是完全正确的,但答案可能是ES6形状:

HTMLInputElementObject.oninput = () => {
  console.log('run'); // Do something
}

Or can be written like below:

或者可以写成如下:

HTMLInputElementObject.addEventListener('input', (evt) => {
  console.log('run'); // Do something
});

回答by kai

instead of id use title to identify your element and write the code as below.

而不是 id 使用标题来标识您的元素并编写如下代码。

$(document).ready(()=>{

 $("input[title='MyObject']").change(()=>{
        console.log("Field has been changed...")
    })  
});