使用Jquery的表单元素的占位符

Placeholder for form elements using Jquery

本文关键字:占位符 元素 表单 使用 Jquery      更新时间:2023-09-26

首先,我想说的是,这个问题的目的不是问它是如何完成的,而是了解我为什么这样做。

我想为表单元素创建占位符文本,在玩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个文本框中工作,这就是我的问题:不同的占位符在运行时存储在哪里?函数的实例是否为绑定到的每个字段保留?如果是,从长远来看,这会对性能产生任何影响吗?

感谢您的时间和帮助:)

函数的实例是否为绑定到的每个字段保留?

是的。每次调用placehold()时,都会创建新的事件处理程序函数。idplaceholder的值作为您创建的闭包的一部分保留。

如果是,从长远来看,这会对性能产生任何影响吗?

按照你的做法,你调用placehold()的每个元素都会有一点开销。不过,我不担心,它确实可以忽略不计。

Nicer将重复使用事件处理功能:

function placeholderEmpty() { 
    var $this = $(this);
    if ( $this.val() == $this.data("placeholder") ) {
        $this.val(""); 
    }        
}
function placeholderDefault() {
    var $this = $(this);
    if ( $this.val() == "" ) {
        $this.val( $this.data("placeholder") ); 
    }        
}
function placehold(id,placeholder) {
  $("#"+id).data("placeholder", placeholder) 
  .focusin(placeholderEmpty)
  .focusout(placeholderDefault)
  .trigger("focusout");
} 

下一步将是一个插件(注意使用另一个闭包):

$.fn.extend({
  placehold: function () {
    var placeholderEmpty   = function () { /* ... */ };
    var placeholderDefault = function () { /* ... */ };
    return function(placeholder) {
      this.data("placeholder", placeholder) 
      .focusin(placeholderEmpty)
      .focusout(placeholderDefault)
      .trigger("focusout");
      return this; 
    }
  }();
});

用作

$('#uname').placehold('Please enter a username');
$('#pword').placehold('Please enter a password');
$('#email').placehold('Please enter an email address');
$('.manyTextFields').placehold('All get the same text & behavior.');