代码之家  ›  专栏  ›  技术社区  ›  BVernon

如果用户未确认,撤消模糊时的文本更改

  •  0
  • BVernon  · 技术社区  · 6 年前

    当用户离开文本框时,我想弹出一个确认对话框,询问他们是否确定要进行更改。如果他们回答否,那么我希望文本框撤销他们的更改。

    有没有一种非常简单的方法可以做到这一点,或者我必须手动跟踪初始值是多少?

    (我知道如何确认,只是询问撤销部分)

    0 回复  |  直到 6 年前
        1
  •  3
  •   Scott Marcus    6 年前

    您确实需要存储旧值,但使用一个在每次确认更改后设置的变量非常简单:

    let lastConfirmedValue = "";  // Last good value is stored here
    
    document.querySelector("input").addEventListener("change", function(evt){
      if(confirm("Are you sure?")){
        lastConfirmedValue = this.value;  // Update the last committed value
      } else {
        evt.preventDefault();             // Cancel the event
        this.value = lastConfirmedValue;  // Put old value back
      }
    });
    <input>

    自从你问起 defaultValue ,让我向您展示它的工作原理:

    let txt1 = document.getElementById("one");
    let txt2 = document.getElementById("two");
    
    
    console.log("Box 1 defaultValue: " + one.defaultValue,
                "Box 2 defaultValue: " +  two.defaultValue);
                
    // Now change the values of both
    txt1.value = "something";
    txt2.value = "somthing else";
    
    console.log("Box 1 defaultValue: " + one.defaultValue,
                "Box 2 defaultValue: " +  two.defaultValue);
                
    // Now change the values of both again
    txt1.value = "abc";
    txt2.value = "xyz";
    
    console.log("Box 1 defaultValue: " + one.defaultValue,
                "Box 2 defaultValue: " +  two.defaultValue);
    <input id="one">
    <input id="two" value="CT">
        2
  •  0
  •   BVernon    6 年前
        3
  •  0
  •   Tom O.    6 年前

    您可以监听适当的事件,然后在这些事件发生时采取行动:

    const inputEl = document.querySelector('#inputEl');
    let temp;
    
    //Update the temp value each time we focus on the input
    inputEl.addEventListener('focus', e => {
      temp = e.target.value;
    });
    
    //Confirm that the user wants to keep their changes
    inputEl.addEventListener('change', e => {
      var confirmed = confirm('Are you sure you want to save these changes?');
      if (!confirmed) {
        e.target.value = temp;
      }
    })
    <label for="inputEl">Enter a value</label>
    <input id="inputEl" type="text">
    推荐文章