2011-03-06 30 views
0
$(document).ready(function() { 
    $('.watermark').focus(function() { 
     if (this.className == 'watermark') 
     { 
      this.className = ''; 
      this.value = ''; 
     } 
    }); 

    $('.watermark').blur(function() { 
     if (this.value == '') 
     { 
      this.className = 'watermark'; 
      this.value = 'Type here'; 
     } 
    }); 
}); 

我有这个代码块,除了它不是动态的,它可以完美地工作。我想知道是否有一种优雅的方式来动态地将值重置为原始值。我在想,也许如果你定义了原始文本的ID或其他类型的属性,你可以重置它,或者你可以使用变量或数组或元组。 SO认为做这件事的最好方法是什么?如何重构此代码块以简化和动态?

+2

我重构通常延伸我[代码传递给谷歌(http://www.google.com/search? q = jquery + watermark + plugin&ie = utf-8&oe = utf-8&aq = t&rls = org.mozilla:en-US:official&client = firefox-a)and [see if if](http://plugins.jquery.com/project/ updnWatermark)我[已重新发明](http://plugins.jquery.com/project/TinyWatermark)[wheel](http://code.google.com/p/jquery-watermark/)。 – 2011-03-06 21:05:21

回答

1

如何将值存储到输入的其他属性?

$(document).ready(function() { 
    $('.watermark').focus(function() { 
     if (this.className == 'watermark') 
     { 
      this.className = ''; 
      this.title = this.value; 
      this.value = ''; 
     } 
    }); 

    $('.watermark').blur(function() { 
     if (this.value == '') 
     { 
      this.className = 'watermark'; 
      this.value = this.title; 
     } 
    }); 
}); 
+0

是的,非常感谢!^_ ^ – 2011-03-06 21:05:26

0

在这种情况下我更喜欢使用JavaScript回落使用HTML5(placeholder attrinute)。

function supports_input_placeholder() { 
    var i = document.createElement('input'); 
    return 'placeholder' in i; 
} 
$(document).ready(function() { 
    if (!supports_input_placeholder()) 
    { 
    $('input').each(function(){ 
     $(this).val($(this).attr('placeholder')) 
    }); 
    $('input').focus(function() { 
     if (this.className == 'watermark') 
     { 
      this.className = ''; 
      this.value = ''; 
     } 
    }); 

    $('input').blur(function() { 
     if (this.value == '') 
     { 
      this.className = 'watermark'; 
      this.value = $(this).attr('placeholder'); 
     } 
    }); 
    } 

}); 

此脚本将检测原始占位符是否可用,如果不是,则它将从占位符属性中获取文本并进行模拟。

0

你只需将它存储在一个变量,如果它的范围的每一个元素:

$(function() { 
    $('.watermark').each(function() { 
    var lead = $(this).val(); 
    $(this).focus(function() { 
     if ($(this).val() == lead) $(this).val(''); 
    }).blur(function() { 
     if ($(this).val() == '') $(this).val(lead); 
    }); 
    }); 
});