javascript参数传递动态动作处理程序 [英] javascript parameter passing in dynamic action handler

查看:70
本文介绍了javascript参数传递动态动作处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要动态创建几个Div,我需要向他们添加onmouseover事件。但是,JAVASCRIPTdiv.onmouseover = handler无法传入参数。 如何在这些动态事件处理程序中传递参数?

I need to create several Divs dynamically, and I need to add "onmouseover" event to them. However, the JAVASCRIPT "div.onmouseover = handler" can't pass in parameters. how can I pass parameters in those dynamic event handlers?

推荐答案

您可以利用关闭来做到这一点:

You can take advantage of closures to do this:

function createHandlerFor(a, b, c) {
    return function(event) {
        // This function will be called later, and it has access
        // to 'a', 'b', and 'c'
    };
}

或使用命名函数(我的偏好,所以调用堆栈等更清晰);

Or using a named function (my preference, so call stacks and such are clearer);

function createHandlerFor(a, b, c) {
    function myNiftyHandler(event) {
        // This function will be called later, and it has access
        // to 'a', 'b', and 'c'
    };
    return myNiftyHandler;
}

使用:

div.onmouseover = createHandler(1, 2, "three");

...或通过 addEventListener (标准)或 attachEvent (IE< 8)。

...or hook it up via addEventListener (standards) or attachEvent (IE < 8).

虽然你可以内联定义处理程序,但是所以关闭你定义它的范围内的所有东西。使用单独的函数并传递参数可以使闭包尽可能小,这对内存管理非常有用。

Although you could define the handler inline, doing so "closes over" everything that's in scope where you define it. Using a separate function and passing it parameters keeps the closure as small as possible, which is useful for memory management.

闭包并不复杂,但它们有一些有趣的属性。 此处了解更多信息。

Closures are not complicated, but they have some interesting properties. More here.

这篇关于javascript参数传递动态动作处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆