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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can take advantage of closures to do this:
Or using a named function (my preference, so call stacks and such are clearer);
Use:
…or hook it up via
addEventListener(standards) orattachEvent(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.