我正在开发一个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);