gpt4 book ai didi

javascript - 保存输入值,以便在用户留空时恢复为默认值

转载 作者:行者123 更新时间:2023-11-30 10:45:07 25 4
gpt4 key购买 nike

我尝试创建一个变量 oldValue 然后如果当前值 === "" 那么它将变回 oldValue 因为我使用的是 for 循环,所以我可以明确地说出值是什么。

代码正在改变 input 元素周围的 div 这就是为什么有 .parentNode

谁能告诉我如何获取输入值并保存它,或者我的代码哪里出错了。

var inputFocus = function(){
var inputs = document.getElementsByClassName("inputNoFocus");
for (i = 0; i < inputs.length; i++){
var input = inputs[i];
var oldValue = this.value;

input.addEventListener("focus", function(){

if(this.value === this.value){
this.value = "";
}
this.parentNode.parentNode.setAttribute("class", "inputFocus");
}, false);

input.addEventListener("blur", function(){
if(this.value === ""){
this.value = oldValue;
}
this.parentNode.parentNode.setAttribute("class", "noHover");
}, false);
}
}();

最佳答案

试试这个:

(function() {
var inputs = document.getElementsByClassName("inputNoFocus");

function setEmptyVal() {
if (this.value == this.defaultValue) this.value = "";
this.parentNode.parentNode.setAttribute("class", "inputFocus");
}

function setDefaultVal() {
if (this.value == "") this.value = this.defaultValue;
this.parentNode.parentNode.setAttribute("class", "noHover");
}

for (i=0; i<inputs.length; i++) {
var input = inputs[i];

input.defaultValue = input.value;
input.addEventListener("focus", setEmptyVal, false);
input.addEventListener("blur", setDefaultVal, false);
}
})();

这是 the fiddle .

关于javascript - 保存输入值,以便在用户留空时恢复为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8840931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com