摘要 - 我正在使用文本比较工具。我有两个功能 - Excel-Parser,它从Excel文件中获取数据并动态/编程更改输入文本。
- 文本比较函数会听取输入字段中任何更改并运行文本比较逻辑的功能。
我是jQuery的新手,但曾尝试使用EventListeners,Onput,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。
您可以使用突变处理器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()
,并且需要设置输入元素的value
属性以使其与属性保持同步。(如changeIt()
函数中所示。
您可以使用onkeydown。
var a = document.getElementById("test");
a.addEventListener('onkeydown', recInput);
function recInput(e) {
console.log("Sucess!", e.key);
}