![](/img/trans.png)
[英]Event listener for input's value change through changing with .val() in jQuery?
[英]Changing input value on input, without affecting change listener?
我有文字輸入。 它具有一個change
和一個input
偵聽器。 在input
偵聽器中,如果輸入的值為“刪除”,則將其刪除。 change
偵聽器僅警告“已更改”。
當前行為:
沒有“已更改”。 鍵入“刪除”並停止編輯時會發出警告,因為比較基准也已更改。
期望的行為:
我想查看“已更改”。 根據編輯開始時的值發出警報,而忽略修改期間進行的所有程序更改。
最簡單的方法是什么?
Playgorund:
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.