简体   繁体   English

更改输入的输入值,而不影响更改侦听器?

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

I have a text input. 我有文字输入。 It has a change and an input listener. 它具有一个change和一个input侦听器。 In the input listener, I delete the value of the input, if it is "delete". input侦听器中,如果输入的值为“删除”,则将其删除。 The change listener simply alerts "Changed.". change侦听器仅警告“已更改”。

Current behaviour: 当前行为:

There is no "Changed." 没有“已更改”。 alert when I type "delete" and stop editing, because the comparison base is changed as well. 键入“删除”并停止编辑时会发出警告,因为比较基准也已更改。

Desired behaviour: 期望的行为:

I want to see the "Changed." 我想查看“已更改”。 alert based on the value at the start of the editing, ignoring all the programatic changes made during the modification. 根据编辑开始时的值发出警报,而忽略修改期间进行的所有程序更改。

What is the simplest way of doing this? 最简单的方法是什么?

Playgorund: Playgorund:

  1. Click the input. 单击输入。
  2. Delete the content. 删除内容。
  3. Type "delete". 键入“删除”。
  4. See how the text is deleted. 查看如何删除文本。
  5. Click somewhere else. 单击其他位置。
  6. See how the "Changed." 查看如何“更改”。 alert is not displayed. 显示警报。

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

My current solution is to add an attribute that I store the initial value in on each focus event, and compare it to the current value at the time of the blur event. 我当前的解决方案是在每个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