私はjQueryプラグインを作成するのが初めてなので、これを行う方法が少しわかりません。プラグインは、テキストおよびパスワード入力内のヒントとしてラベルを表示するためのものです。それは一種の単純なものです-要素のフォーカスでは、ラベルは非表示になっています。また、ドキュメントの読み込み時に、ブラウザがフィールドフォームを自動入力したかどうかを確認します。自動入力した場合は、ラベルが非表示になります。私が抱えている問題は、他のフィールドのオートコンプリートです。これを解決するために、要素のonblurイベントとkeyupイベントに関数をバインドして、他のフォーム要素をループし、それらがオートコンプリートされているかどうかを調べようとしています。
これが注釈付きのコードです。
(function( $ ){
$.fn.innerLabels = function( ) {
return this.each(function() {
var $this = $(this);
// Initialise all form elements with class
$this.each(function() {
var lngth = $(this).val().length;
if(lngth > 0){
$(this).parent().children('label').hide();
}else{
$(this).parent().children('label').show();
};
});
// onfocus event - clears label
$this.focus(function() {
$this.parent().children('label').hide();
});
// onblur/keyup event re-enstates label if length of value is zero or hides if autocompleted.
$this.bind("blur keyup",function() {
// check all fields in case of autocomplete <- this is the problem
$(this).each(function() {
var lngth = $(this).val().length;
//alert(lngth);
if(lngth > 0){
$(this).parent().children('label').hide();
}else{
$(this).parent().children('label').show();
};
});
});
});
};
})( jQuery );
これを行うことでトリガーされます。
$(document).ready(function(){
$('.txtbox').innerLabels();
});
.txtboxは、これを使用するフォームテキストおよびパスワードフィールドに追加するクラスです。
スコープの問題だと思います。最後の$(this).eachが問題です。.txtboxクラスですべての要素をループするのではなく、イベントが発生している入力の値をループします。クラス名をプラグインに追加したくないのは、コードが追加されて柔軟性が低下するためです。
これに関するアドバイスをいただければ幸いです。
乾杯
グレッグ