7

イベント ハンドラー関数に引数を渡すにはどうすればよいですか? これにより、ページの読み込み時に関数が実行されますが、これは望ましい効果ではありません。いくつかの異なるテキストボックス、ドロップダウンの組み合わせに対して実行するには、このルーチン「validateText」が必要です。テキスト/ドロップダウンの組み合わせごとに 1 つ作成する代わりに、「validateText」を再利用できますか??

//add blur event handler to the textbox with jQuery when the page is finished loading
    $(document).ready(function() {
        $("#myTextbox").blur(validateText($("#myTextbox"), $("#Select1")));
    })


    function validateText(textbox, dropdown) {

        var message = $("#message");
        var isValid = false;
        //get the value the user type in
        var textboxValue = $(textbox).val();

        //get the options from the lookup
        var options = $("option", dropdown);

        //loop through the options and compare it to "value"
        options.each(function() {
            var optValue = $(this).val();
            if (optValue === textboxValue) {
                isValid = true;
            }
        });

        if (!isValid)
            message.text(textboxValue + " is not a valid value from the list.");
        else
            message.text(textboxValue + " is perfectly valid.");
    }
4

2 に答える 2

11

バインディングを使用して、追加のパラメーターをイベント リスナーに渡します。

http://docs.jquery.com/Events/bind

$(document).ready(function() {
    $("#myTextbox").bind("blur", [ $("#myTextBox"), $("#Select1")], validateText);
})

次に、event.data からデータにアクセスします。

function validateText(event) {
  textBox  = event.data[0];
  dropdown = event.data[1];
}
于 2009-08-04T22:47:40.697 に答える
5

ロード時に呼び出す理由は、関数名を引数とともに渡すとアクティブに呼び出されるためです。このように、validateText の呼び出しを匿名関数でラップすることにより、探しているものを効果的に模倣できます。

$(document).ready(function() {
    $("#myTextbox").blur(function(){
        // Since in your original example you used $("#myTextbox") as an arg, this mimics it
        validateText($(this), $("#Select1"));
    });
});

匿名関数は、'this' キーワードを使用しているため、#myTextbox から textarea などに変更すると、最初のセレクターとのスケーリングが少し改善されるはずです。=)

于 2009-08-04T22:37:00.703 に答える