如果输入文本被JavaScript更改,则检测更改

时间:2019-05-16 01:13:00

标签: javascript input event-handling onchange

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

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

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。

2 个答案:

答案 0 :(得分:1)

您可以使用MutationObserver API来完成此操作。

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

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()函数中所示。

答案 1 :(得分:0)

您可以为此使用onkeydown

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

a.addEventListener('onkeydown', recInput);

function recInput(e) {
  console.log("Sucess!", e.key);
}
相关问题