开发者

How to pass parameters (other than event) to event handlers?

The following code renders 3 buttons with label "1", "2" and "3". Clicking on each button will alert the label.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                var a = [1, 2, 3];
                $.each(a, function(i, ai) {
                    $('<button />').text(i).appendTo('body')
                        .click(function() {alert(i);});
                });
            });
        </script>
    </head>
    <body>
    </body>
</html>

However, if I replace function() {alert(i);} with foo and define function foo() { alert(i); }, I will get an error of variable i is not defined.

So how to pass parameters (other than event) to event handlers? I think defining the event han开发者_如何转开发dler (foo() in this case) as a named function will make the code cleaner if the event handler is long and complicated.


If you look at the documentation for bind, you'll see it has an optional eventData parameter. So for example this would work:

function foo(e)
{
    alert(e.data.theI);
}

$(function ()
{
    var a = [1, 2, 3];
    $.each(a, function (i, ai)
    {
        $('<button/>').text(i).appendTo('body').bind("click", {theI: i}, foo);
    });
});


$(function() {
                var a = [1, 2, 3];
                $.each(a, function(i, ai) {
                    $('<button />').text(i).appendTo('body')
                        .click(function() { foo.apply(this,[i]);});
                });
            });


function foo( i )
{
   alert( i + " : " + $(this).text() );
}


A third method, and the way I usually do it is to invoke a function that returns your handler. Like this:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script type="text/javascript">
            var bindFoo = function(x) {
                return function() {alert(x);};
            };
            $(function() {
                var a = [1, 2, 3];
                $.each(a, function(i, ai) {
                    $('<button />').text(i).appendTo('body')
                        .click(bindFoo(i));
                });
            });
        </script>
    </head>
    <body>
    </body>
</html>

I'm using x in the binding function only to distinguish it from i in the main code block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜