简体   繁体   中英

jQuery, how can I pass args to event handler?

How can I pass args to the event handler function? This runs the function on page load which is not the desired effect. I need this routine "validateText" to run against several different textbox, dropdown combinations. Can I reuse "validateText" instead of creating one per text/dropdown combination??

//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.");
    }

Use binding to pass extra parameters to an event listener:

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

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

Then access the data from event.data:

function validateText(event) {
  textBox  = event.data[0];
  dropdown = event.data[1];
}

The reason it calls at load is because handing over a function name with arguments actively calls it. You can effectively mimic what you're looking for by wrapping the call to validateText in an anonymous function like so.

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

The anonymous function, since it's using the 'this' keyword, should scale a little better with your initial selector if you change it from #myTextbox to textarea or whatever. =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM