优化此Javascript代码

时间:2010-12-20 07:29:00

标签: javascript jquery optimization

我想知道是否有办法让这段代码更有效率,我正在尝试改进自己的代码,但我觉得我需要反馈,这一部分:

$(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...');
    });
});

7 个答案:

答案 0 :(得分:1)

/* ==========================================================
 * 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'添加idear(多事件绑定) 备注:   如果你愿意,你可以使用这个代码而不使用“iif”扩展。   那你必须写:

if((event.type === 'focus' || event.type === 'change') && $this.isEdited('Buscar...'))

答案 1 :(得分:1)

我认为这是以最佳方式编写代码的最简单方法

$(function(){
    $('#buscar').bind('focus change blur' , function(){
  //write ur codes here
});

答案 2 :(得分:0)

我会选择下面的代码。它隔离了您需要的函数(测试空字符串,或测试没有值或占位符文本)。另外,我不相信change功能是改变颜色的正确位置;相反,它应该在focusblur函数中,您也可以在其中更改值。

此外,如果您只是在寻找输入字段的占位符方法,那么您已经为自己设置了许多方法,您可以在其中设置文本和CSS样式。此外,HTML 5为此目的具有placeholder属性 - 请参阅http://davidwalsh.name/html5-placeholder。一些更好的占位符插件甚至使用HTML 5,如果不支持,则回退到JS。

无论如何,这是代码:

$.fn.isValBlank = function() {
    return $.trim($(this).val()) == "";
};

$.fn.isInputBlank = function() {
    return (($(this).isValBlank() || ($(this).val() === 'Buscar...'));
};

$(function(){
    $('#buscar').focus(function(){
        var val = $(this).val();
        if ($(this).isInputBlank()) {
            $(this).val('');
            $(this).css({'color':'#000'});
        }
    });

    $('#buscar').blur(function(){
        if ($(this).isValBlank()) {
            $(this).css({'color':'#999'});
            $(this).val('Buscar...');
        }
    });
});

答案 3 :(得分:0)

如果是未来并且HTML5无处不在,或者每个人只使用当前版本的Safari,Chrome和Firefox,那么您可以删除大部分代码并将其替换为:

<input name="something" id="buscar" placeholder="Buscar...">

但是,因为在撰写本文时,它仍然是现在,你可以像这样收紧事情:

function isEdited(el,placeholder){
  placeholder = typeof placeholder == 'undefined' ? 'Buscar...' : placeholder;
  return $.trim( $(el).val() ) === placeholder;
}

$('#buscar').focus(function(){
  if( isEdited(this) )
      $(this).val('');
}).change(function(){
  if( isEdited(this) )
      $(this).css({'color':'#999999'});
  else
      $(this).css({'color':'#000000'});
}).blur(function(){
    if( $.trim( $(this).val() ) )
       $(this).val('Buscar...');
});

如果您需要做很多这样的事情,可以考虑使用jQuery Placeholder Plug-in。它使用placeholder属性,因此它是HTML5友好的。

另外,

答案 4 :(得分:0)

有了额外的知识,感谢@ deceze的见解,我建议将大部分逻辑分解为单个函数。基本上所有这些条件都是检查字段是否为空。

另外,我正在为任何类型的空格添加一个检查,因为单个" "与两个空格" "一样无关紧要。

function isTextFieldEmpty(text, placeholder) {
    var onlyWhitespace = /^\s+$/;
    return (text == "" || onlyWhitespace.test(text) || text == placeholder);
}

然后,您可以对所有活动重复使用此功能 - focusblurchange

$(function() {

    // to avoid repeating this text everywhere..
    var placeholder = 'Buscar...';

    $('#buscar').focus(function() {
        if (isTextFieldEmpty(this.value, placeholder)) {
            $(this).val('');
        }
    });

    $('#buscar').blur(function() {
        if (isTextFieldEmpty(this.value, placeholder)) {
            $(this).val(placeholder);
        }
    });

    $('#buscar').change(function() {
        if (isTextFieldEmpty(this.value, placeholder)) {
            $(this).css({ color: '#999' });
        }
        else {
            $(this).css({ color: '#000' });
        }
    });

});

答案 5 :(得分:0)

JavaScript可以访问的HTML input elements have a defaultValue属性。在讨论占位符文本输入值时,您可以使用它来帮助使代码更具可重用性。无论如何,这并不完美......但

$(function(){

    $("input[type='text']").focus(textInputFocusHandler).change(textInputChangeHandler).blur(textInputBlurHandler);

});

function hasUserValue(textInput) {
    return (textInput.value!=textInput.defaultValue && /^\s+$/.test(textInput.value)==false && textInput.value!=="");
}

function textInputFocusHandler(event) {
    if(!hasUserValue(event.target)) event.target.value = "";
}

function textInputChangeHandler(event) {
    if(!hasUserValue(event.target)) event.target.style.color = "#999";
    else event.target.style.color = "#000";
}

function textInputBlurHandler(event) {
    if(!hasUserValue(event.target)) event.target.value = event.target.defaultValue;
}

答案 6 :(得分:0)

快速优化:

$(function(){
$('#buscar').focus(function(){
    var t = $(this);
        var v = $.trim(t.val());
 if(v === '' || 'Buscar...'){
    $(this).val('');
        }
}).change(function(){
    var t = $(this);
        var v = $.trim(t.val());
 (v === '' || 'Buscar...' ? t.css({'color':'#999999'}) : t.css({'color':'#000000'}))
}).blur(function(){
    var t = $(this);
        var v = $.trim(t.val());
    if(v === '')
       t.val('Buscar...');
});
});