0

我正在开发一个用于文本框内提示的 jQuery 插件。到目前为止,我的工作正常。但是,我需要为具有原始提示的文本框实现“全部删除”方法。

我能想到的唯一方法是循环并将值与标题进行比较:

$('input').each(function() {
  if ($(this).prop('title') == $(this).val()) {
    $(this).val('');
  }
});

但是,问题在于我可以根据标题设置提示或在选项中覆盖它。所以..我不想依赖标题。

问题:是否有内置的 jQuery 机制来链接元素与特定数据,或者是否有其他解决方案?

这是我当前的代码:

(function ($) {
    var settings = {
        normColor: '#000000',
        hintColor: '#808080',
        hint: ''
    };

    var methods = {
        init: function (options) {
            var $this = $(this);

            // try to set original text color of input
            settings.normColor = $this.css('color');

            // set hint to the title
            settings.hint = $this.prop('title'); 

            // merge default settings with user provided options
            // we need to supply a blank array as the first
            // argument so the default settings are not overwritten
            settings = $.extend({}, settings, options);

            return this.each(function () {
                $this.css('color', settings.hintColor);
                $this.val(settings.hint);

                // begin on focus
                $this.on('focus', function () {
                    if ($this.val() == settings.hint) { // if what's entered is NOT the hint
                        $this.val('');

                        // return to normal color
                        $this.css('color', settings.normColor);
                    }
                }); // end on focus

                // begin on blur
                $this.on('blur', function () {
                    if ($this.val().length == 0 || $this.val() == msg) {
                        $this.val(settings.hint);
                        $this.css('color', settings.hintColor);
                    }
                }); // end on blur
            });
        },
        remove: function () {
            return this.each(function () {
                alert('remove');
            });
        },
        removeAll: function() {
            return this.each(function () {
                alert('remove all');
            });
        }
    };

    /// begin main function
    $.fn.hint = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.hint');
        }
    };
})(jQuery);
4

0 回答 0