簡體   English   中英

更改輸入的輸入值,而不影響更改偵聽器?

[英]Changing input value on input, without affecting change listener?

我有文字輸入。 它具有一個change和一個input偵聽器。 input偵聽器中,如果輸入的值為“刪除”,則將其刪除。 change偵聽器僅警告“已更改”。

當前行為:

沒有“已更改”。 鍵入“刪除”並停止編輯時會發出警告,因為比較基准也已更改。

期望的行為:

我想查看“已更改”。 根據編輯開始時的值發出警報,而忽略修改期間進行的所有程序更改。

最簡單的方法是什么?

Playgorund:

  1. 單擊輸入。
  2. 刪除內容。
  3. 鍵入“刪除”。
  4. 查看如何刪除文本。
  5. 單擊其他位置。
  6. 查看如何“更改”。 顯示警報。

 var input = document.querySelector('input'); input.addEventListener('change', function() { alert('Changed.'); }); input.addEventListener('input', function() { input.value = input.value.replace(/^delete$/, ''); }); 
 <input value="example" /> 

我當前的解決方案是在每個focus事件上添加一個用於存儲初始值的屬性,並將其與blur事件發生時的當前值進行比較。

 var input = document.querySelector('input'); input.addEventListener('focus', function() { this.setAttribute('data-value-on-focus', this.value); }); input.addEventListener('blur', function() { if (this.getAttribute('data-value-on-focus') !== this.value) alert('Changed.'); }); input.addEventListener('input', function() { this.value = this.value.replace(/^delete$/, ''); }); 
 <input value="example" /> 

暫無
暫無

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

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