Passing javascript in a dynamic action handler

I need to create multiple Divs dynamically, and I need to add an onmouseover event to them. However, JAVASCRIPT "div.onmouseover = handler" cannot pass parameters. how to pass parameters to these dynamic event handlers?

+3
source share
3 answers

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

Using:

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

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

, "" , , . , , .

, . .

+5

closure.

div.onmouseover = function(){ handler(arguments,here); }
+1

You can use closure to do this:

myParam = "test";
div.onmouseover = function(){ alert(myParam); }
0
source

Source: https://habr.com/ru/post/1739700/


All Articles