我想知道是否有办法让这段代码更有效率,我正在努力改进我自己的代码,但我觉得我需要反馈,这部分:
$(function(){
$('#buscar').focus(function(){
if(($(this).val() === '') || ($(this).val() === ' ') || ($(this).val() === 'Buscar...'))
$(this).val('');
}).change(function(){
if(($(this).val() === '') || ($(this).val() === ' ') || ($(this).val() === 'Buscar...'))
$(this).css({'color':'#999999'});
else
$(this).css({'color':'#000000'});
}).blur(function(){
if(($(this).val() === '') || ($(this).val() === ' '))
$(this).val('Buscar...');
});
});
最佳答案
/* ==========================================================
* speed and readable improvment
* ========================================================== */
$(function(){
$('#buscar')
.bind('focus change blur', function(){
var $this = $(this);
if(event.type === 'focus' || event.type === 'change')
$this
.iff($this.isEdited('Buscar...'))
.val('')
.end();
else if(event.type === 'blur')
$this
.iff($this.isEdited(null))
.val('Buscar...')
.end();
});
});
(function($){
'$:nomunge'; // Used by YUI compressor.
$.fn.iff = function( test ) {
var elems = !test || $.isFunction( test )
&& !test.apply( this, Array.prototype.slice.call(arguments, 1) )
? []
: this;
return this.pushStack( elems, 'iff', test );
};
})(jQuery);
$.fn.isEdited = function(placeholder) {
if(typeof placeholder !== 'string')
placeholder = '';
var val = $(this).val();
return $.trim(val) === '' || val === placeholder;
};
编辑:重写代码以添加来自“Mohan Ram”的想法(多事件绑定(bind)) 评论: 如果愿意,您也可以在没有“iif”扩展名的情况下使用此代码。 那么你必须写:
if((event.type === 'focus' || event.type === 'change') && $this.isEdited('Buscar...'))
关于javascript - 优化此 Javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4487662/