【发布时间】:2011-11-19 11:16:00
【问题描述】:
我在网上找到了这个:
var x = 0; // count for array length
$("input.placeholder").each(function(){
x++; //incrementing array length
});
var _values = new Array(x); //create array to hold default values
x = 0; // reset counter to loop through array
$("input.placeholder").each(function(){ // for each input element
x++;
var the_default = $(this).val();
var default_value = $(this).val(); // get default value.
_values[x] = default_value; // create new array item with default value
});
var current_value; // create global current_value variable
$('input.placeholder').focus(function(){
current_value = $(this).val(); // set current value
var is_default = _values.indexOf(current_value); // is current value is also default value
if(is_default > -1){ //i.e false
$(this).val(''); // clear value
}
});
$('input.placeholder').focusout(function(){
if( $(this).val() == ''){ //if it is empty...
$(this).val(current_value); //re populate with global current value
}
});
如您所见,它抓取value 属性中的文本并将其设置为default_value。然后它会根据默认值检查current_value。
我遇到了问题。
在这个例子中,我们有一个像这样的元素:
<input type="text" class="placeholder" value="potato">
如果用户关注和取消关注输入,效果很好 - 删除并重新填充“土豆”。
但是,假设用户输入“ioqiweoiqwe”,然后取消关注输入(填写表单的其余部分“)。然后他们返回我们的输入并删除所有文本,然后单击另一个字段。输入将重新填充“ioqiweoiqwe” - 实际上,我们希望它重新填充default_value。我该如何做到这一点?
此致, 一个 jQuery 小块。
注意:我在这里设置了一个 jsfiddle... 在一些 cmets 之后:http://jsfiddle.net/xmhCz/
【问题讨论】:
标签: javascript input placeholder