如果输入文本被JavaScript更改

如果输入文本被JavaScript更改

本文介绍了如果输入文本被JavaScript更改,则检测更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘要-我正在研究一种文本比较工具.我有两个功能-一个excel解析器,可从excel文件中获取数据并动态/以编程方式更改输入文本.
-文本比较功能可侦听输入字段中的任何更改并运行文本比较逻辑.

Summary- I am working on a text-comparison tool. I have two functions- an excel-parser, which fetches data from excel file and changes the input-text dynamically/programmatically.
- a text comparison function listens for any changes in the input field and runs text-comparison logic.

我是jQuery的新手,但是曾经尝试使用eventListener,oninput,onchange,onpaste等进行JS.注意:以下代码段说明了这种情况.但是,没有这样的按钮单击.

I am new to jQuery but have tried JS with eventListeners, oninput, onchange, onpaste, etc.Note: The following code snippet explains the situation. However, there is no such button click.

var a = document.getElementById("test");

function assignValue() {
  a.value = "Hello World";
}
a.addEventListener('input', recInput);

function recInput() {
  console.log("Sucess!");
}
<input id="test">
<button onclick="assignValue()">Click to add text</button>

是否可以使用JS捕获更改?如果没有,我愿意使用jQuery.

Is there any way of capturing changes using JS? If not, I am open to using jQuery.

推荐答案

您可以使用 MutationObserver API 来做到这一点.

You can use the MutationObserver API to do this.

注册一个将处理不断变化的属性的回调函数.

Register a callback function that will deal with the changing attribute.

const input = document.getElementById('name');
const observer = new MutationObserver(list => {
  console.log("New Value: ", list[0].target.value);
})
observer.observe(input, {
  attributes: true,
  childList: false,
  subtree: false
});

function changeIt() {
  const randomString = Math.random() >= 0.5 ? "one" : "two";
  input.setAttribute("value", randomString);
  input.value = randomString;
}
<input placeholder="Enter some text" name="name" id="name" />
<button onclick='changeIt()'>Push me
</button>

您将需要使用setAttribute(),并且需要设置Input元素的value属性,以使其与该属性保持同步. (如changeIt()函数中所示.

You'll need to use setAttribute() and you'll need to set the Input element's value property to keep it in sync with the attribute. (as seen in the changeIt() function.

这篇关于如果输入文本被JavaScript更改,则检测更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 08:03