0

Is there a way to parse data to a function from the event listener ?

I have this:

div.addEventListener('mousedown',run(id),false);

function run(e,id){
   console.log(id);
}

Thing is it executes straight away. The other problem is - if i want to parse the variable id, and the run function recieves e for the event, how do you parse any thing else =/ It's a bit confusing to work out what order e is (before or after your designated variables that you want to parse)

The current work around so far was to assign id to window so its basically a global... but i'm wondering if parsing via the event is possible at all ?

4

2 回答 2

0

事件处理程序不直接接受参数,您正在调用函数 run(id),而不是传递处理程序,这是传递它的方式(使用匿名函数)

https://developer.mozilla.org/en/docs/DOM/element.addEventListener

div.addEventListener('mousedown',function(e){
  doSomething(id);
},false);

function doSomething(id){
  console.log(id);
}
于 2013-02-17T07:32:14.007 回答
0

一种方法是创建一个新的侦听器函数,其中id变量已经绑定到您想要的值,如下所示:

function newListener(id) {
    var listener = function(e) {
        console.log(id);
    }
    return listener;
}
div.addEventListener('mousedown',newListener(id),false);

newListener(id)定义了一个新函数,其中id变量当时的值在该函数内部可用。然后,当按下鼠标按钮时,javascript 环境将调用该函数。

于 2013-02-17T07:26:03.947 回答