javascript - 优化此 Javascript 代码

标签 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...');
    });
});

最佳答案

/* ==========================================================
 * 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/

相关文章:

javascript - 在 css 和 html 中响应左右图像

jquery - 我想在单击行中的按钮时取消行上的事件处理程序

jquery - 监听添加的表行

java - 如何将大量数据从数据库存储到 XML(速度问题,第三部分)?

c# - 同时解码和显示多个 H264 视频的最快方法 C#

javascript - 通过 Javascript 请求 MS Access 数据

javascript - Javascript 的 XSS 安全 html 解码

javascript - 下拉菜单打开另一个下拉菜单 - CodeIgniter

javascript - 如何将 bootstrap-datetimepicker 设置为今天凌晨 12 点的日期

python - 节食 py2exe 和 matplotlib