繁体   English   中英

jQuery,我如何将args传递给事件处理程序?

[英]jQuery, how can I pass args to event handler?

如何将args传递给事件处理函数? 这将在页面加载上运行该功能,这不是所需的效果。 我需要这个例程“validateText”来运行几个不同的文本框,下拉组合。 我可以重用“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.");
    }

使用绑定将额外参数传递给事件侦听器:

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];
}

它在加载时调用的原因是因为移交带有参数的函数名称会主动调用它。 通过在匿名函数中包含对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或其他任何内容,则应使用初始选择器进行更好的扩展。 =)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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