簡體   English   中英

如果輸入文本被JavaScript更改,則檢測更改

[英]Detect change, if input-text is changed by JavaScript

摘要-我正在研究一種文本比較工具。 我有兩個功能-一個excel解析器,可從excel文件中獲取數據並動態/以編程方式更改輸入文本。
-文本比較功能偵聽輸入字段中的任何更改並運行文本比較邏輯。

我是jQuery的新手,但是嘗試使用eventListeners,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。

您可以使用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()函數所示。

您可以為此使用onkeydown

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

a.addEventListener('onkeydown', recInput);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM