I wrote this function:
我写了这个函数:
jQuery(document).ready(function() {
jQuery('input[type=text]').each( function(i) {
thisval = jQuery(this).val();
jQuery(this).blur( function() {
if (jQuery(this).val() == '') {
jQuery(this).val(thisval);
}
}); // end blur function
jQuery(this).focus( function() {
if (jQuery(this).val() == thisval) {
jQuery(this).val('');
};
});// end focus function
}); //END each function
}); // END document ready function
It's designed to get the value of an input, then if the user clicks away without entering a new value, the old value returns. This works properly with one of the inputs on the page, but not the others. However, when I remove the .blur and .focus functions and just use alert(thisval); it alerts the name of each input, so something is wrong with my function, but I can't figure out what. Any help?
它旨在获取输入的值,然后如果用户点击而不输入新值,则返回旧值。这适用于页面上的一个输入,但不适用于其他输入。但是,当我删除.blur和.focus函数并只使用alert(thisval);它警告每个输入的名称,所以我的功能出了问题,但我无法弄清楚是什么。有帮助吗?
2 个解决方案
#1
1
thisval is a global variable so it is replaced with each loop. Make it local [stick var in front of it] and it should work like magic.
thisval是一个全局变量,因此它被每个循环替换。让它本地[在它前面的变量]它应该像魔术一样工作。
You should not just keep creating jQuery(this) over and over again. That is very inefficient. jQuery(this) is expensive. You should store one copy in a variable and use the variable.
你不应该一遍又一遍地继续创建jQuery(this)。这是非常低效的。 jQuery(这个)很贵。您应该将一个副本存储在变量中并使用该变量。
#2
5
You need var
when declaring your variable so it's not a global one being shared, like this:
在声明变量时需要var,因此它不是共享的全局变量,如下所示:
var thisval = jQuery(this).val();
Also since you're dealing specifically with text inputs you can just use the .value
DOM property, like this:
此外,由于您专门处理文本输入,您可以使用.value DOM属性,如下所示:
jQuery(function() {
jQuery('input[type=text]').each(function(i) {
var thisval = this.value;
jQuery(this).blur( function() {
if (this.value == '') this.value = thisval;
}).focus( function() {
if (this.value == thisval) this.value = '';
});
});
});
#1
1
thisval is a global variable so it is replaced with each loop. Make it local [stick var in front of it] and it should work like magic.
thisval是一个全局变量,因此它被每个循环替换。让它本地[在它前面的变量]它应该像魔术一样工作。
You should not just keep creating jQuery(this) over and over again. That is very inefficient. jQuery(this) is expensive. You should store one copy in a variable and use the variable.
你不应该一遍又一遍地继续创建jQuery(this)。这是非常低效的。 jQuery(这个)很贵。您应该将一个副本存储在变量中并使用该变量。
#2
5
You need var
when declaring your variable so it's not a global one being shared, like this:
在声明变量时需要var,因此它不是共享的全局变量,如下所示:
var thisval = jQuery(this).val();
Also since you're dealing specifically with text inputs you can just use the .value
DOM property, like this:
此外,由于您专门处理文本输入,您可以使用.value DOM属性,如下所示:
jQuery(function() {
jQuery('input[type=text]').each(function(i) {
var thisval = this.value;
jQuery(this).blur( function() {
if (this.value == '') this.value = thisval;
}).focus( function() {
if (this.value == thisval) this.value = '';
});
});
});