JQuery将输入掩码应用于字段onfocus并删除onblur,以避免占位符文本出现问题

问题描述:

我有一个出生日期文本字段:

I have a date of birth text field:

<input type="text" id="dob" name="dob" placeholder="Date of Birth" />

我正在使用jQuery插件(Charl van Niekerk的占位符文本)来确保旧版浏览器看到占位符文本。到目前为止一切都很好。

I'm using a jQuery plugin (Charl van Niekerk's Placeholder text) to make sure that older browsers see the placeholder text. All good so far.

当点击我的出生日期字段时,我想从占位符文本切换到输入掩码。为此,我正在使用另一个插件(http://digitalbush.com/projects/masked-input-plugin/)。

When my date of birth field is clicked on, I want to switch from the placeholder text to an input mask. For that I'm using another plugin (http://digitalbush.com/projects/masked-input-plugin/).

但是我只想激活输入掩盖onfocus,并将其删除onblur,否则它会阻止占位符文本显示。

However I only want to activate the input mask onfocus, and remove it onblur, otherwise it stops the placeholder text from being shown.

我需要类似的东西:

$(document).ready(function() {    
    $('#dob').focus(function() {  
        $.mask.definitions['~']='[+-]';
        $('#dob').mask('99/99/9999');  
    });
    $('#dob').blur(function() {
        // Something here to unmask?   
    });  
});

此代码目前不起作用。任何想法?

This code doesn't work at the moment. Any ideas?

阅读插件代码,应该可以这样做(未经测试):

Reading the plugin code, it should be possible to do this (untested):

(function($) {
  $(document).ready(function() {
    $('#dob').focus(function() {
      $.mask.definitions['~']='[+-]';
      $(this).mask('99/99/9999');
    }).blur(function() {
      $(this).unmask();
    });
  });
})(jQuery);

注意我添加了(function($){})(jQuery) - 我相信它很好练习以这种方式包装所有代码。

Note that I added (function($){})(jQuery) - I believe it is good practice to wrap all your code this way.