【发布时间】:2011-09-13 20:11:24
【问题描述】:
首先我想提一下,这个问题的目的不是询问它是如何完成的,而是要了解为什么我这样做的方式有效。
我想为表单元素创建占位符文本,在玩 jquery 时我想出了以下代码:
function placehold(id,placeholder) // id of element and placeholder text
{
$("#"+id).val(placeholder); //initialize form field
$("#"+id).focusin(function() //on focus
{
if ($(this).val()==(placeholder))
{
$(this).val(null);
/*if input's value is placeholder then empty
input and wait for value */
}
});
$("#"+id).focusout(function() //on lost focus
{
if ($(this).val()==(""))
{
$(this).val(placeholder); //reset val to placeholder text if empty
}
});
}
即使我在多个字段上调用该函数,这也会起作用,例如,
placehold('uname','Please enter a username');
placehold('pword','Please enter a password);
placehold('email','Please enter an email address');
在上述情况下,它将按预期在所有 3 个文本框中工作,这就是我的问题: 运行时不同的占位符存储在哪里?是为其绑定的每个字段保留的函数实例吗?如果是,从长远来看,这会对性能产生影响吗?
感谢您的时间和帮助:)
【问题讨论】:
标签: javascript jquery forms placeholder