简体   繁体   English

如何使用 Javascript 捕获输入更改事件?

[英]How to capture input changes event using Javascript?

Given an input element, I know we can use this to capture input changes,给定一个输入元素,我知道我们可以用它来捕捉输入变化,

$("input").on("change", function() { ... });

So that, when users type text in the input box, the above function will be triggered.这样,当用户在输入框中输入文字时,上面的 function 就会被触发。

However, my use-case is that, the input is being updated by a button click, not by user typing text directly.但是,我的用例是,通过单击按钮而不是通过用户直接输入文本来更新输入。 And seems cannot use the above code to capture the input changes event.并且似乎无法使用上面的代码来捕获输入更改事件。

Any other approaches?还有其他方法吗?

You need to bind your button with your field by updating the value attribute inside the button callback function.您需要通过更新按钮回调 function 中的value属性来将按钮与字段绑定。 Then use the value wherever.然后在任何地方使用该value

const button = document.getElementById("btn");
const field = document.getElementById("field");

button.addEventListener("click", event => {
  // Update your input attrs here
  field.value = "Updated"
})

How about attaching a 'click' event listener to the button, and reading or modifying the input box according in that event handler?将“click”事件侦听器附加到按钮,并根据该事件处理程序读取或修改输入框怎么样?

$("button").on("click", function() {... });

or或者

$("button").click(function() {... });

Since you have said that you are generating the button with js, you could add the event listener while the button is being generated:既然您说您正在使用 js 生成按钮,您可以在生成按钮时添加事件侦听器:

<div id="app"></div>
<script>
    /* inside your code to generate your button */
    var btn = document.createElement("button"); // your code to generate the button
    var app = document.getElementById("app").appendChild(btn); // the code to add the button to the document 
    btn.addEventListener('click', function() {console.log("It works!")}); // add an event listner to the button while you still have a reference to it
</script>

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

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