[英]Focus and blur events triggered on wrong element
我正在尝试一次为多个输入设置默认值,在焦点上移除该值并在输入为空时再次设置模糊值。 为了实现这一点,使用jQuery,我有这个代码:
var settings = {
value: '',
focusColor: 'black',
blurColor: '#CCC',
value : 'test'
};
$.each($('input'), function(index, el) {
$(el).on('blur', function(ev) {
$el = $(this);
console.log('blur ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == '')
$el.attr('value', settings.value).css('color', settings.blurColor);
}).on('focus', function(ev) {
console.log('focus ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == settings.value)
$(this).attr('value', '').css('color', settings.focusColor);
});
$(el).trigger('blur');
});
有这个HTML:
<input id="text" type="text" />
<input id="email" type="email" />
问题是,如果我专注于第一个输入并且紧接着第二个输入,则触发的事件是:聚焦于第一个输入,第一个输入时模糊并再次聚焦第一个输入。 因此,如果我在第一个中键入内容,然后再次关注第二个,在第一个中,它将不会删除示例文本并将删除我输入的内容。
你可以在这里看到(不)工作的例子。 打开JavaScript控制台,您会清楚地看到错误的行为。
你的意思是这样的:
$('input').on('blur', function(ev) {
$el = $(this);
console.log('blur ' + $el.va() + ' ' + $el.attr('id'));
if ($el.val() == '')
$el.attr('value', settings.value).css('color', settings.blurColor);
})
$('input').on('focus', function(ev) {
$el = $(this);
console.log('focus ' + $el.val() + ' ' + $el.attr('id'));
if ($el.val() == settings.value) {
$(this).val("");
$(this).css('color', settings.focusColor);
}
});
演示: http : //jsfiddle.net/fnBeZ/4/
你忘记了焦点事件中的集$ el。
$.each($('input'), function(index, el) {
$(el).on('blur', function(ev) {
$el = $(this);
console.log('blur ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == '')
$el.attr('value', settings.value).css('color', settings.blurColor);
}).on('focus', function(ev) {
$el = $(this); // <-- should update $el
console.log('focus ' + $el.attr('value') + ' ' + $el.attr('id'));
if ($el.attr('value') == settings.value)
$(this).attr('value', '').css('color', settings.focusColor);
});
$(el).trigger('blur');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.