2012-07-08 69 views
0

上我想一次爲多輸入設定的默認值,取消對焦點值和模糊重新設置,如果輸入的是空的。爲了實現這一目標,使用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控制檯,您會看到明顯的錯誤行爲。

回答

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'); 
}); 
+0

這樣一個愚蠢的錯誤......謝謝!這是在我面前,我無法看到它:) – davids 2012-07-08 11:48:25

+0

你也應該聲明'$ el' var'(除非你明確地希望它是全球性的某種原因)。 – nnnnnn 2012-07-08 11:52:44

+0

它發生:-)很高興我可以幫忙 – Sindre 2012-07-08 11:55:14

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/

+0

感謝您的答案,是完全正確的,但我使用每個循環的原因是因爲我必須添加一些邏輯取決於將修改行爲的輸入狀態。所以我必須接受@ Mantion的答案,因爲它適合我的目的 – davids 2012-07-08 11:51:42

相關問題