当用户离开文本框时,我要弹出确认消息,询问他们是否确定要进行更改。如果他们回答“否”,那么我希望文本框撤消他们的更改。
是否有一种非常简单的方法来执行此操作,还是我必须手动跟踪自己的初始值?
(我知道如何做确认,只是询问撤销部分)
答案 0 :(得分:3)
您确实必须存储旧值,但是对每个已确认的更改都设置一个变量很简单:
STRINGTABLE
BEGIN
IDS_STRING703 "Versión: %d.%d.%d.%d"
END
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);
答案 1 :(得分:0)
defaultValue是我一直在寻找的东西:
答案 2 :(得分:0)
您可以监听适当的事件,然后在这些事件发生时采取措施:
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">