在错误的元素上触发焦点和模糊事件

时间:2012-07-08 11:33:49

标签: javascript jquery focus onblur onfocus

我正在尝试一次为多个输入设置默认值,在焦点上移除该值并在输入为空时再次设置模糊值。为了实现这一点,使用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" />

问题是,如果我专注于第一个输入并且紧接着第二个输入,则触发的事件是:聚焦于第一个输入,第一个输入时模糊并再次聚焦第一个输入。因此,如果我在第一个中键入内容,然后再次专注于第二个内容,那么它将不会删除示例文本并删除我输入的内容。

您可以看到(不)工作示例here。打开JavaScript控制台,您会清楚地看到错误的行为。

2 个答案:

答案 0 :(得分:1)

你是说这样的意思吗?

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

DEMO:http://jsfiddle.net/fnBeZ/4/

答案 1 :(得分:1)

您忘记了焦点事件中的设置$ 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');
});
相关问题