将多个参数与事件对象一起传递给事件处理程序--javascript [英] Pass multiple arguments along with an event object to an event handler - javascript

查看:119
本文介绍了将多个参数与事件对象一起传递给事件处理程序--javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用Function.prototype.bind的情况下将多个参数与事件对象一起传递给事件处理程序?

How can one pass multiple arguments along with an event object to an event handler without using Function.prototype.bind ?

事件处理程序中有一个闭包。

The event handler has a closure in it.

以下基本代码不起作用,

The below basic code won't work,

element.addEventListener(click,eventHandler(eventObj + arguments),false);

function eventHandler(eventObj + arguments) {
  return function(){}; //a closure
}

我不知道如何传递事件对象和其他同时参数到事件处理程序。

I don't know how to pass event object and other arguments at the same time to an event handler.

更新:

我甚至尝试过使用匿名函数的addEventListener。这样做,似乎控件从未到达回调函数内的闭包。

I have even tried using anonymous function inside addEventListener. Doing so, it seems that the control never reached to the closure inside the callback function.

element.addEventListener("click", function(e){
    var data = {'event':e, 'args':arguments};
    eventHandler(data);
  }, false);

function eventHandler(data) {
  return function(){  //this function is never executed
    console.log(JSON.stringify(data));
  };
}


推荐答案

所以,如果我理解正确,您希望向元素添加事件侦听器,并配置在添加侦听器时存在的一些其他数据,以便在调用时将其传递给侦听器。如果这就是你想要做的,你只需要一个合适的关闭。假设您想要将附加数据存储在对象中,请执行以下操作:

So if I understand correctly, you want to add an event listener to the element, and configure some additional data that exists at the time you're adding the listener to be passed to the listener when it's called. If that's what you want to do, you just need a proper closure. Something like this, assuming you want to store the additional data in an object:

var extra_data = {one: "One", two: "Two"};

var make_handler = function (extra_data) {
  return function (event) {
    // event and extra_data will be available here
  };
};

element.addEventListener("click", make_handler(extra_data));

这篇关于将多个参数与事件对象一起传递给事件处理程序--javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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