【问题标题】:How to refactor this code block to be simple and dynamic?如何将此代码块重构为简单和动态?
【发布时间】:2011-03-06 20:55:56
【问题描述】:
$(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认为最好的方法是什么?

【问题讨论】:

标签: javascript jquery refactoring watermark


【解决方案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;
        }
    });
});

【讨论】:

    【解决方案2】:

    在这种情况下,我更喜欢将 html5(placeholder attrinute) 与 javascript fall back 一起使用。

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

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

    【讨论】:

      【解决方案3】:

      如果它的作用域是每个元素,你可以将它存储在一个变量中:

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

      【讨论】:

        猜你喜欢
        • 2019-11-08
        • 1970-01-01
        • 1970-01-01
        • 2010-09-08
        • 1970-01-01
        • 1970-01-01
        • 2019-06-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多