javascript - How to pass a parameter to a event's handler - Stack Overflow

How to pass a parameter to a event's handler?Here's what am trying to do, but it doesn'

How to pass a parameter to a event's handler?

Here's what am trying to do, but it doesn't work:

for (var i = 0; i < myobj.length; i++) {
myobj[i].onmouseover = myfun(myobj[i]);
}

The following doesn't work neither:

myobj[i].onmouseover = myfun.call(myobj[i]);
myobj[i].onmouseover = function () {myfun(myobj[i]);};
myobj[i].onmouseover = function () {myfun.call(myobj[i]);}; 

Am primarily interested in why it doesn't work, and solution in the same style.

How to pass a parameter to a event's handler?

Here's what am trying to do, but it doesn't work:

for (var i = 0; i < myobj.length; i++) {
myobj[i].onmouseover = myfun(myobj[i]);
}

The following doesn't work neither:

myobj[i].onmouseover = myfun.call(myobj[i]);
myobj[i].onmouseover = function () {myfun(myobj[i]);};
myobj[i].onmouseover = function () {myfun.call(myobj[i]);}; 

Am primarily interested in why it doesn't work, and solution in the same style.

Share Improve this question edited Jan 26, 2023 at 20:12 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Apr 25, 2012 at 12:16 Xah LeeXah Lee 17.6k9 gold badges39 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

Just use a creator function for your handlers to encapsulate the parameter to pass on.

function createHandler( param ) {
  return function() {
    myfun( param );
  }
}

for (var i = 0; i < myobj.length; i++) {
  myobj[i].onmouseover = createHandler( myobj[i] );
}

The reason your approach doesn't work is, because you don't pass on a function reference, but the result of a function call. So in your first example myfun( myobj[i] ) is evaluated and the result is passed on as the event handler.

I think, what you really mean is, that in case the event is fired, the function shall be evaluated. To do so you either have to pass the parameter via some global var or as a dataset property.

The cleaner solution, however, is to have a generator function as shown above.

Another approach is to use the fact that onmouseover will be invoked as a method (not a function) on the DOM element which fires the event.

In other words, write your code as if you expected someone to do this:

obj = xahlees();
obj.onmouseover();

Here's a solution:

for (var i = 0; i < myobj.length; i++) {
  myobj[i].onmouseover = function() { myFun(this) };
}

I've uploaded a more plete example .

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743722572a4496072.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信