1

私は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クラスですべての要素をループするのではなく、イベントが発生している入力の値をループします。クラス名をプラグインに追加したくないのは、コードが追加されて柔軟性が低下するためです。

これに関するアドバイスをいただければ幸いです。

乾杯

グレッグ

4

2 に答える 2

0

jqueryでは、next()関数を使用して兄弟を選択できます

$(this).next()

次のものを選択します。

next()の詳細

于 2011-05-29T02:40:49.387 に答える
0

コードを見るだけで、ぼかし時に初期化コードを再度実行しようとしているように見えます。これは事実ですか?その場合は、その共通コードを関数にリファクタリングし、イベント ハンドラーから呼び出すだけです。

(function($) {
    $.fn.innerLabels = function() {
        var $self = this;
        var hideElements = function() {
            $self.each(function() {
                var lngth = $(this).val().length;
                if (lngth > 0) {
                    $(this).parent().children('label').hide();
                } else {
                    $(this).parent().children('label').show();
                };
            });  
        };

        hideElements();

        return $self.focus(function() {
            $(this).parent().children("label").hide();
        }).bind("blur keyup", hideElements);
    };
})(jQuery);

イベントハンドラーの割り当ては、一致する要素のセット内のすべてのアイテムに対して機能するため、いくつかのリファクタリングの後.each、(ステートメントで) 呼び出しの必要性もわかりませんでした。return

それがあなたが求めていたものであることを願っています。

于 2011-05-29T03:08:21.180 に答える